1

I call a component on a HTML page like this:

<app-my-component></<app-my-component>

What I want it's link a guard canDeactivate with the component my-component. This component is never called by a route, so I don't add a path in RouterModule. I use it in 2 different pages.

How to link the component and the guard without adding something like that:

{ path: 'my-component', component: MyComponent, canDeactivate: [CanDeactivateGuard] }

2 Answers2

0

This may not be a good solution. But, you can actually use *ngIf based on your requirements to show or hide.

<app-my-component *ngif="some logic here"></<app-my-component>

without routing path, you won't get the guard feature.

Roy
  • 1,189
  • 7
  • 13
  • I want to use CanDeactivate for keeping the user from losing data by leaving the page. The problem if I use `*ngIf` is I will not know if the user go to the previous page or change page with the navbar (for example). But it works when I use a guard with canDeactivate – Jordan PANTIN Nov 12 '19 at 15:06
  • I know that, but without declaring the component in router, you won't be able to get that guard feature. – Roy Nov 12 '19 at 15:12
  • So I cannot use `` if I want to get the guard feature ? I must call the component with a route ? – Jordan PANTIN Nov 12 '19 at 15:15
  • Yes, as far as I know. – Roy Nov 12 '19 at 15:19
  • Rather than having `*ngif` which will require a boolean flag in all the component's class file, I would suggest you to create a structural directive as `*hasPermission`. Follow the resource https://juristr.com/blog/2018/02/angular-permission-directive/ – user3875919 Nov 12 '19 at 16:16
  • I want to use the guard after the render of the page for keeping the user from losing data by leaving the page before submit. So I don't need a condition for knowing if the page can be rendered or not. – Jordan PANTIN Nov 13 '19 at 08:40
0

The Guard is just like a service. You can inject it into a component and call the desired method . But it will not behave as a Guard (stop routing etc) and you will have to manage the logic yourself.