【问题标题】:Angular 4+. Assign value to variable角 4+。为变量赋值
【发布时间】:2018-07-09 19:42:33
【问题描述】:

我试图在我的 html 中以角度 4+ 分配一个变量。这可能吗?

我试图实现的是将比较分配给一个变量,所以我不必在所有情况下都保持相同。

这是我想要实现的示例:

<mat-list-item role="list" *ngFor="let o of examles;" role="listitem">

     <span *ngIf="o.type == 'EXAMPLE_TYPE'"> some text</span>
 // here more divs
     <span *ngIf="o.type == 'EXAMPLE_TYPE'"> other text</span>
 // more divs...
     <span *ngIf="o.type == 'EXAMPLE_TYPE'"> last text</span>  

</mat-list-item>

所以,我的问题是,有没有办法声明类似的东西?

<div #isExampleType="o.type == 'EXAMPLE_TYPE'" >

然后在 *ngIf="isExampleType" 中使用它...

【问题讨论】:

  • 你可以在检索数据的逻辑上使用 .map 函数来做到这一点。 http.get(...).map(o => {o.type == 'EXAMPLE_TYPE';return o;})
  • @LeonardoNeninger 是的,我知道,但我想知道我是否可以在 de html 中做到这一点
  • 我不知道你为什么要这样做。我认为可以帮助您的另一种方法是创建一个接收“o”变量的指令,您可以从控制器中将其作为 ViewChild 引用
  • 相关问题(不是完全欺骗),stackoverflow.com/questions/38582293/…
  • 来自the Angular documentation: A template reference variable is often a reference to a DOM element within a template. It can also be a reference to an Angular component or directive or a web component.

标签: javascript angular angular-directive


【解决方案1】:

你可以试试这样的:

<input #myHiddenValue type="hidden" value="ASDFG">

<div *ngIf="myHiddenValue.value==='ASDFG'">{{ myHiddenValue.value }}</div>

【讨论】:

  • 这和我做的几乎一样,我只想在一个地方给我真假对比
  • @JpCrow 你正在做的事情会导致语法错误,因为模板变量不能这样使用。虽然这个答案是一个 hack,但它是可行的。
【解决方案2】:

这种特殊情况可以通过组件方法方便地解决:

<span *ngIf="isExampleType(o)"> some text</span>

或管道:

<span *ngIf="o | exampleType"> some text</span>

两者对性能的影响几乎为零

没有好的内置方法来分配这样的变量。 #isExampleType 是模板变量,不能用于此目的。

最接近的是结构指令中的let,例如ngIf

<mat-list-item role="list" *ngFor="let o of examles;" role="listitem">
  <ng-container *ngIf="o.type == 'EXAMPLE_TYPE'; let isExampleType">
     <span *ngIf="isExampleType"> some text</span>
     ...
  </ng-container>
</mat-list-item>

但是,副作用是它提供了隐藏行为。由于isExampleType 被认为是真实的,o.type == 'EXAMPLE_TYPE' || ' '; let isExampleType 的诡计将不起作用。

肮脏的解决方法是改用ngFor。它将按预期工作,但会提供不合理的性能开销:

<mat-list-item role="list" *ngFor="let o of examles;" role="listitem">
  <ng-container *ngFor="let isExampleType of [o.type == 'EXAMPLE_TYPE']">
     <span *ngIf="isExampleType"> some text</span>
     ...
  </ng-container>
</mat-list-item>

一个不错的选择是自定义ngVar 结构指令,就像here 解释的那样。

【讨论】:

  • 谢谢,我想知道有没有一种方法可以在 html 中完成所有操作。 :(
  • 我猜 ngVar 是要走的路。
猜你喜欢
  • 1970-01-01
  • 2018-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-18
  • 2016-01-24
  • 1970-01-01
相关资源
最近更新 更多