简体   繁体   中英

Angular: Binding on ngIf inside ngFor

I am trying to populate a list with condition on each list-item, where the condition is changeable through user input.
For example:
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>

Here, I have a list, ['ABC', 'def', 'GHI'] , some of whose elements I want to display always (condition: true) and for the rest, I have put the condition in a variable (check) .
The list is being loaded correctly, but on changing the condition variable (check) through a dropdown, the changes are not being reflected (list is not updated).
Any help would be really appreciated!

You have to use an object make the "checked" property linked to the array.
Also, you should use <ng-container> in order to not generate any HTML if the condition is false.

<!-- HTML -->
<ng-container *ngFor="let item of some">
  <div *ngIf="item.condition">
    {{item.name}}
  </div>
</ng-container>

<select [(ngModel)]="myFakeForm.check">
  <option [value]="true">true</option>
  <option [value]="false">false</option>
</select>

// TS
public myFakeForm = { check: true }
public some = [
    {name: 'ABC', condition: true},
    {name: 'def', condition: this.myFakeForm.check},
    {name: 'GHI', condition: true}
];
  1. You should use public access for fields resolved in the template
  2. this.check is passed as value not a reference to the component field - that's why it's not changing on dropdown select.

So in order to fix this, you have to pass the "check" flag somehow by reference. You could change the check from boolean to some object for example: check = {value: boolean = true}; or think of more generic approach :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM