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.
*ngIf work like this *ngIf="expression" where the expression is replaces with the simple Javascript statement which returns boolean . But you use one = and it means that you assign the someValue to the item property and if the value is not falsy it will return you true .
To get started using template reference variables, simply create a new Angular component or visit an existing one. To create a template reference variable, locate the HTML element that you want to reference and then tag it like so: #myVarName .
The *ngIf directive is most commonly used to conditionally show an inline template, as seen in the following example. The default else template is blank.
Template Reference Variable in angular is used to access all the properties of any element inside DOM. It can also be a reference to an Angular component or directive or a web component. Template Reference Variable can refer to the following – DOM element. Directives.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With