我怎样才能使用' as'重新分配templateRefVar?

时间:2018-04-28 13:30:46

标签: angular

我试图重新分配Angular模板中提供的templateRefVar。我可以使用' as'使用关键字为其所属的元素赋值,如下例所示:

<input value="hello" #templateRefVar>

<!-- This works! -->
<div *ngIf="templateRefVar.value as value">
  I can output {{ value }}
</div>

但是我很难使用&amp;&amp;运算符如果我扩展* ngIf,因为它会抛出错误:

<!-- I can't get it to work using && -->
<div *ngIf="(templateRefVar.value as value) === 'hello' && templateRefVar.value">
  I cannot output {{ value }} and get an error.
</div>

我实际上正在寻找一种方法来重新分配值而无需* ngIf指令。我希望有一个标准的api,我不知道这可以让我像下面的例子一样动态重新分配模板变量(带着一厢情愿的想法......)

<!-- Wish this worked : ( -->
<div *ngIf="templateRefVar.value === 'hello'" #reassignment="templateRefVar.value as value">
 Hoping I can output {{ value }}
</div>

更新评论:

为方便起见,如果我需要像表格那样进行验证:

<!-- check if password.errors is not null before attempting to show validation messages regarding password.errors -->
<ng-container *ngIf="!verifyPassword.pristine && password.errors as errors"
   <!-- Using errors as shorter syntax rather than password.errors on different validation checks below -->
   <div>
     {{ errors.minlength }}
   </div>
   <div>
     {{ errors.nextError }}
   </div>
   <div>
     {{ errors.someOtherValidationMessage }}
   </div>
</ng-container>

这就是为什么我希望Angular有一个api支持templateRefVar重新分配,以防我有一个比上面更复杂的* ngIf。

0 个答案:

没有答案