update *ngFor with ChangeDetectorRef

237 views Asked by At

I've got a little problem and one of these days where I can't seem to find a good solution for it. I tried some solutions from similar questions but without success.

When the user is logged out, all links are disabled. Once the user the logged in, some links should only be disabled, when the user does not have the role Admin.

I have read most of the similar questions and came up with the EventEmitterService to call a method in the app.component.ts from the login.component.ts. The called method in app.component.ts calls this.changeDetectorRef.detectChanges().

However, the links are still disabled, although the user logged in has the role Admin.

app.component.ts

export class AppComponent implements OnInit {
  navLinks = [
    { path: 'hello', label: 'Hello' },
    { path: 'administration', label: 'Administration', role: 'admin' }
  ];

  private roles: string[];
  isAdmin = false;

  constructor(
    ...
    private eventEmitterService: EventEmitterService,
    private cdr: ChangeDetectorRef) {
    
  }

  ngOnInit() {
    if (this.eventEmitterService.subsVar === undefined) {
      this.eventEmitterService.subsVar = this.eventEmitterService.
      invokeRoleRefreshFunction.subscribe((name: string) => {
        this.updateRoles();
      });
    }
    ...
  }

  updateRoles() {
    const user = this.tokenStorageService.getUser();

    this.roles = user.roles;
    console.log(this.roles);

    this.isAdmin = this.roles.includes('ROLE_ADMIN');

    this.cdr.detectChanges();
    }
  }

app.component.html

<nav mat-tab-nav-bar>
  <a mat-tab-link
     *ngFor="let link of navLinks"
     [disabled]="link.role === 'admin' && !isAdmin || !isLoggedIn"
     [routerLink]="link.path"
     routerLinkActive #rla="routerLinkActive"
     [routerLinkActiveOptions]="{exact:true}"
     [active]="rla.isActive">
    {{link.label}}
  </a>
</nav>

login.component.ts

export class LoginComponent implements OnInit {

  constructor(private eventEmitterService: EventEmitterService) { }

  onLogin() {
    ...
    this.eventEmitterService.onLogin();
  }
}

Sorry for missing StackBlitz. Hope someone can give me a hint.

Thanks a lot

0

There are 0 answers