Answer the question
In order to leave comments, you need to log in
How to do the right toggle?
When the user is logged in, it displays: "Welcome + username", when yupth logs out, the guard is triggered, and I assign "this.currentUser = null" to "this.currentUser = null". When I log in I get an error Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'null: username'. Current value: 'null: ' . When I exit, I catch this error: TypeError: Cannot read property 'name' of null . If I remove the else, only the 'null' error remains. How to fix?
export class AppComponent implements AfterViewChecked {
toggle: boolean = false;
user:string;
constructor( private authService: AuthService, private cdRef : ChangeDetectorRef) {
}
ngAfterViewChecked() {
let show = this.authService.isLoggedIn();
if (show != this.toggle) { // check if it change, tell CD update view
this.toggle = show;
this.user = this.authService.currentUser.name;
this.cdRef.detectChanges();
}else {
this.user = '';
}
}
}
<li>Welcome {{user}}</li>
logout(): void {
this.currentUser = null;
localStorage.removeItem('currentUser');
}
Answer the question
In order to leave comments, you need to log in
if (show != this.toggle) { // check if it change, tell CD update view
this.toggle = show;
this.user = this.authService.currentUser.name;
} else {
this.user = '';
}
this.cdRef.detectChanges();
this.cdRef.detectChanges()
after assignment.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question