jame2981
jame2981

Reputation: 51

Dynamic update of template on a Component

I want to render another template when the authentication failed:

@Component({
    selector: 'app-root',
    templateUrl: './a.html',
  })
export class AppComponent implements OnInit {
   ngOnInit() {
      if (!this.isAuthenticated()) {
          this.templateUrl = './b.html';
      }
   }
   isAuthenticated(): boolean {
      // return by user authenticate status
   }
}

Upvotes: 0

Views: 68

Answers (1)

LoïcR
LoïcR

Reputation: 5039

What you need is actually a guard and not a redirection or another component.

Create an authentication.guard.ts containing this code:

@Injectable()
export class AuthenticationGuard implements CanActivate {

constructor(
    private router: Router,
    private authenticationService: AuthenticationService,
) {}

public canActivate(): boolean {
    if (this.authenticationService.isLoggued()) {
        return true;
    }

    this.router.navigate(["/login"]);
    return false;
}

}

In your Route definition, specify that the access to a defined component should be protected by this guard:

{ path: "yourRoute", component: DummyComponent, canActivate: [AuthenticationGuard] },

Now every request will be "checked" with this guard. And you are good to go.

Upvotes: 1

Related Questions