Show or hide app-root depending on ngIf on Angular 12+

Discussão em 'Angular' iniciado por Tito, Dezembro 5, 2024.

  1. Tito

    Tito Guest

    I am trying to show/hide a development page from most of people.

    I changed the index.html like:

    <!DOCTYPE html>
    <html lang="en">
    <head>
    </head>
    <body>
    <app-wrapper></app-wrapper>
    </body>
    </html>


    And AppModule like:

    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';


    And wrapper component as:

    import { ChangeDetectorRef, Component, OnInit } from '@angular/core';
    import { environment } from '../../environments/environment';

    @Component({
    selector: 'app-wrapper',
    template: `
    <div *ngIf="isPasswordCorrect; else passwordPrompt">
    <app-root></app-root>
    </div>
    <ng-template #passwordPrompt>
    <button (click)="checkPassword()">Enter Password</button>
    </ng-template>
    `
    })
    export class WrapperComponent implements OnInit {
    isPasswordCorrect = false;

    constructor(private cdr: ChangeDetectorRef) {}

    ngOnInit(): void {
    console.log('Environment:', environment.environmentName);
    if (environment.environmentName === 'dev') {
    const correctPassword = 'your-password-here';
    const storedPassword = localStorage.getItem('sitePassword');

    console.log('Stored Password:', storedPassword);
    console.log('Correct Password:', correctPassword);

    if (storedPassword === correctPassword) {
    this.isPasswordCorrect = true;
    this.cdr.detectChanges(); // Trigger change detection
    }
    } else {
    this.isPasswordCorrect = true;
    this.cdr.detectChanges(); // Trigger change detection
    }
    }

    checkPassword(): void {
    const correctPassword = 'your-password-here';
    let password = prompt('Please enter the password to access this site:');
    if (password === correctPassword) {
    localStorage.setItem('sitePassword', password);
    this.isPasswordCorrect = true;
    this.cdr.detectChanges(); // Trigger change detection
    } else {
    alert('Incorrect password. The page will reload.');
    window.location.reload(); // Reload the page
    }
    }
    }
    import { AppComponent } from './app.component';
    import { WrapperComponent } from './wrapper/wrapper.component';

    @NgModule({
    declarations: [
    AppComponent,
    WrapperComponent
    ],
    imports: [
    BrowserModule
    ],
    providers: [],
    bootstrap: [WrapperComponent]
    })
    export class AppModule { }


    even when it was true the app-root was not shown, but I could be able to see it's components tree using the Angular Development tools. Does anyone have any solution for it?

    Continue reading...

Compartilhe esta Página