[英]Access template variable in *ngIf
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. 我试图在元素上定义模板变量并使用其隐藏属性来识别元素是否实际存在于DOM中,然后基于该元素显示另一个元素。 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. 正如您所看到的,包含属性
ngIf
和wpHasAnyPermission
元素上的模板变量都没有返回值。
What I want to eventually do is to use resendEmailBtn
and editAccountBtn
in ngIf
of hr
to decide displaying the divider. 我最终想要做的是在
ngIf
of hr
使用resendEmailBtn
和editAccountBtn
来决定显示分隔符。
What is the best way to solve this ? 解决这个问题的最佳方法是什么? I want to avoid dealing with component code.
我想避免处理组件代码。 Try to solve this with in HTML.
尝试用HTML解决这个问题。
The variable is not available outside the element where *ngIf
is applied. 在应用
*ngIf
的元素之外,该变量不可用。
<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. 和
divi
只能在<template>
元素中使用。
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.
当查询的元素添加到DOM时,它只有一个值。 If it's within an
*ngIf
that evaluates to false
the value will be null
. 如果它在评估为
false
的*ngIf
,则该值将为null
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.