Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular 4. remove a component in the constructor based on an if

I want to add protection to components. If a user doesn't have permission to see this component it wont be rendered.

I have tried putting my if in the constructor and return false but it still renders.

I also added the if to the template itself but then I didn't see the view but the component is still alive and it adds complexity to the code as I need to maintain several places of the same if.

Is there a way to tell the component to not render at all ?

 constructor( private userService: UserService) {
    if (this.userService.isAllowed("see_trade_groups") === false) {
           return;
    }
}
like image 439
Amit Wagner Avatar asked Jun 23 '26 12:06

Amit Wagner


1 Answers

For that purpose you can see CanActivate. Put it on the component route and it will do the job you want.

In that you can write a logic, based on which the route will be navigated or not.

like image 164
Suren Srapyan Avatar answered Jun 26 '26 05:06

Suren Srapyan