Angular:在 ngFor 内绑定 ngIf

我正在尝试在每个列表项上使用条件填充列表,其中条件可以通过用户输入进行更改。

例如:

app.component.ts


private check = true;

private some = [

    {name: 'ABC', condition: true},

    {name: 'def', condition: this.check},

    {name: 'GHI', condition: true}

];

app.component.html


<div *ngFor="let item of some">

  <div *ngIf="item.condition">

  {{item.name}}

  </div>

</div>


<select [(ngModel)]="check">

  <option [value]="true">true</option>

  <option [value]="false">false</option>

</select>

在这里,我有一个列表,['ABC', 'def', 'GHI']我想始终显示其中的一些元素,(condition: true)而对于其余的,我将条件放在一个变量(check)中。

列表正在正确加载,但在(check)通过下拉列表更改条件变量时,没有反映更改(列表未更新)。

任何帮助将非常感激!


蓝山帝景
浏览 153回答 2
2回答

30秒到达战场

您必须使用一个对象将“已检查”属性链接到数组。此外,如果条件为假,您应该使用<ng-container>它以便不生成任何 HTML。<!-- HTML --><ng-container *ngFor="let item of some">&nbsp; <div *ngIf="item.condition">&nbsp; &nbsp; {{item.name}}&nbsp; </div></ng-container><select [(ngModel)]="myFakeForm.check">&nbsp; <option [value]="true">true</option>&nbsp; <option [value]="false">false</option></select>// TSpublic myFakeForm = { check: true }public some = [&nbsp; &nbsp; {name: 'ABC', condition: true},&nbsp; &nbsp; {name: 'def', condition: this.myFakeForm.check},&nbsp; &nbsp; {name: 'GHI', condition: true}];

慕少森

您应该对模板中解析的字段使用公共访问权限this.check作为值而不是对组件字段的引用传递 - 这就是它在下拉选择中没有改变的原因。所以为了解决这个问题,你必须以某种方式通过引用传递“检查”标志。例如,您可以将检查从布尔值更改为某个对象:&nbsp;check = {value: boolean = true};或者考虑更通用的方法:)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript