简体   繁体   中英

How to reference element controlled by *ngIf directive without template reference in Angular 6?

I want to obtain a reference to the element controlled by the *ngIf directive without using a template reference in Angular 6.

For example, I have:

<a *ngIf="allowAccessTo()" [routerLink]="['/home']" class="nav-item nav-link">Home</a>

I would like to have a reference to that element, and specifically the href/pathname from the [routerLink] , inside my allowAccessTo() method but without having to add a template reference to the element.

Is there a way to do this?

I plan to use the href/pathname from the element to call into my role guard service.

I have it working if I pass the route into the allowAccessTo() method ( allowAccessTo('home') ) but would prefer to not have to do that.

This is my primary app navigation so there will be many links like this and even if I added a template reference, I wouldn't know which one to look at inside allowAccessTo() without being able to tell which element caused the allowAccessTo() method to be invoked.

Could you not create a variable in typescript file like: currentRoute and set this variable whenever you need to route? Then, this variable can be accessed in the function allowAccessTo() directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM