本文介绍了在 *ngIf 中访问模板变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在一个元素上定义一个模板变量,并使用它的隐藏属性来识别该元素是否实际存在于 DOM 中,然后基于它显示另一个元素.但是如果有结构指令,模板变量似乎没有返回值.


<div *ngIf="showResendWelcomeEmailButton"><a *wpHasAnyPermission="[{'something': true}]"#resendEmailBtn>重新发送欢迎电子邮件</a>

<div class="pull-right"><a #editAccountBtn>编辑帐户详细信息</a>

rbtn: {{resendEmailBtn?.hidden}}ebtn:{{editAccountBtn?.hidden}}dline:{{divi?.hidden}}

输出是

rbtn:ebtn:假线:

正如您所看到的,包含属性 ngIfwpHasAnyPermission 的元素上的模板变量都没有返回值.

我最终想要做的是在hrngIf中使用resendEmailBtneditAccountBtn来决定显示分隔线.

解决这个问题的最佳方法是什么?我想避免处理组件代码.尝试在 HTML 中解决这个问题.

解决方案

该变量在应用了 *ngIf 的元素之外不可用.


将被替换

<hr class="divider" >

divi 将仅在 元素中可用.

您可以添加

@ViewChild('editAccountBtn') editAccountBtn:ElementRef;

到您的组件类,使其在整个组件模板中可用.当被查询的元素被添加到 DOM 时,它只有一个值.如果它在计算结果为 false*ngIf 内,则该值将为 null.

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.

解决方案

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.

这篇关于在 *ngIf 中访问模板变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 03:31