Angular实现登录页隐藏mat-toolbar、首页显示mat-toolbar及authenticatedUser状态切换后组件不显示的问题求助
Let's break down the likely issues stopping your mat-toolbar from appearing when authenticatedUser switches to 'Yes', and fix them one by one:
Ensure Angular detects the variable change
IfauthenticatedUseris a plain class property (not an Observable/Subject), Angular might miss the update if it happens outside the Angular zone (like in a third-party auth callback). Try either of these fixes:- Wrap the value update in
NgZone.run()to force Angular to recognize the change:import { NgZone } from '@angular/core'; constructor(private ngZone: NgZone) {} // When updating after login: this.ngZone.run(() => { this.authenticatedUser = 'Yes'; }); - Or manually trigger change detection after updating the variable:
import { ChangeDetectorRef } from '@angular/core'; constructor(private cdr: ChangeDetectorRef) {} // After setting authenticatedUser: this.authenticatedUser = 'Yes'; this.cdr.detectChanges();
- Wrap the value update in
Verify the exact value and type of
authenticatedUser
Typos or type mismatches are easy to miss. Add a debug log right after you set the value to confirm it's exactly the string 'Yes' (case-sensitive, no extra spaces):console.log('authenticatedUser:', this.authenticatedUser); console.log('Type:', typeof this.authenticatedUser);If you accidentally set it to a boolean
trueinstead of the string 'Yes', the*ngIfcondition will fail. Adjust your assignment to match the string value your template checks for.Confirm the variable lives in the correct component context
Make sureauthenticatedUseris a property of yourAppComponent(since your template is inapp.component.html). If you're managing auth state in a service, subscribe to it properly in the component to get real-time updates:import { AuthService } from './auth.service'; authenticatedUser: string = 'No'; constructor(private authService: AuthService) { // Assuming your service exposes an Observable for auth state this.authService.authState$.subscribe(isAuthenticated => { this.authenticatedUser = isAuthenticated ? 'Yes' : 'No'; }); }Using an Observable ensures the component gets notified immediately when the auth state changes, which automatically updates the template.
Rule out layout/CSS conflicts
Temporarily remove the*ngIfcondition to check if the toolbar renders at all. This will help you confirm if the issue is with the auth state logic or a layout problem hiding the toolbar:<!-- Test without the condition --> <mat-toolbar color="primary"> <mat-toolbar-row> <button mat-icon-button> <mat-icon (click)="sidenav.toggle()">menu</mat-icon> </button> <h1>Movie Reviews</h1> <span class="menu-spacer"></span> <div> <a mat-button [routerLink]="''" style="margin-left: 1200px;"> LogOut </a> </div> </mat-toolbar-row> </mat-toolbar>
内容的提问来源于stack exchange,提问作者minnu merin alex

