问题
I am trying to define a template variable on an element and use its hidden attribute to identify whether the element is actually present in the DOM and then display another element based on that. But if there is a structural directive, 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 is
rbtn:
ebtn: false
dline:
As you can see both the template variables on elements containing attributes ngIf and wpHasAnyPermission are not returning an values.
What I want to eventually do is to use resendEmailBtn and editAccountBtn in ngIf of hr to decide displaying the divider.
What is the best way to solve this ? I want to avoid dealing with component code. Try to solve this with in HTML.
回答1:
The variable is not available outside the element where *ngIf is applied.
<hr class="divider" *ngIf="false" #divi>
will be replace by
<template let-divi [ngIf]="false">
<hr class="divider" >
</template>
and divi will only be available within the <template> element.
You can add
@ViewChild('editAccountBtn') editAccountBtn:ElementRef;
to your components class, to make it available within the whole components template. It only has a value, when the queried element is added to the DOM. If it's within an *ngIf that evaluates to false the value will be null.
来源:https://stackoverflow.com/questions/45247462/access-template-variable-in-ngif