How to access Angular 2 variable in ngIf

I am trying to define a template variable for an element and use its hidden attribute to determine if the element is actually present in the DOM and then displays another element on it. But if there is a structural directive, the template variable does not seem to return a value.

<hr class="divider" *ngIf="true" #divi> <div *ngIf="showResendWelcomeEmailButton"> <a *wpHasAnyPermission="[{'something': true}]" #resendEmailBtn> Resend Welcome Email </a> </div> <div class="pull-right"> <a #editAccountBtn>Edit Account Details</a> </div> rbtn: {{resendEmailBtn?.hidden}} ebtn: {{editAccountBtn?.hidden}} dline: {{divi?.hidden}} 

Output

 rbtn: ebtn: false dline: 

As you can see, both template variables on elements containing ngIf and wpHasAnyPermission do not return values.

Ultimately, I want to use resendEmailBtn and editAccountBtn in ngIf for hr to select a separator display.

What is the best way to solve this problem? I want to avoid using component code. Try to solve this with HTML.

+5
source share
1 answer

The variable is not available outside the element where *ngIf is used.

 <hr class="divider" *ngIf="false" #divi> 

will be replaced by

 <template let-divi [ngIf]="false"> <hr class="divider" > </template> 

and divi will be available only in the <template> element.

You can add

 @ViewChild('editAccountBtn') editAccountBtn:ElementRef; 

for your component class to make it available for the entire component template. It only matters when the requested item is added to the DOM. If it is in *ngIf , which evaluates to false , the value will be null .

+4
source

Source: https://habr.com/ru/post/1270088/


All Articles