Apply a condition using ngFor and ngIf in angular

2020-02-20 05:40发布

问题:

Hi There I have been trying to filter an array with some success using ngIF and ngFor.

<button *ngFor="let item of items"> <div *ngIf="(item.data.type == 1)"> {{item.data.name}} </div> </button>

This code does only show buttons with name in it for data that has type=1 but it also create empty buttons for each data entry that doesn't have type=1, I can't figure out how to get rid of empty buttons. Any help is much appreciated.

回答1:

I would flip-flop your button and div:

<div *ngFor="let item of items">
    <button *ngIf="(item.data.type == 1)">{{item.data.name}}</button>
</div>

This way only buttons get created for valid items.

You can also use a function in your component:

<button *ngFor="let item of filterItemsOfType('1')">{{item.data.name}}</button>

Where your component has a function:

filterItemsOfType(type){
    return this.items.filter(x => x.data.type == type);
}


回答2:

You can create your own pipe. That is better solution.

@Pipe({
    name: 'somepipe',
})
export class SomePipe {

    transform(objects: any[]): any[] {
        if(objects) {
            return objects.filter(object => {
                return object.data.type === 1;
            });
        }
    }

}

and use it in html in this way:

<button *ngFor="let item of items | somepipe"> <div> {{item.data.name}} </div> </button>


回答3:

<button *ngFor="let item of getItems()">...</button>

getItems() {
  return this.items.filter((item) => item.data.type === 1);
}

where this.items is your array of items somewhere above this function.

Check this out