Search code examples
angularngforangular-ng-if

Need to filter some data from Array in Angular while traversing with *ngFor


I have one array which has some object elements. From below array I want to get the first object which has "mandatory: false" and the first element which has "mandatory: true".

From the below list I need to get State and City in UI.

countryDetailsArray: Array(5)
0: {id: 278, name: "State", mandatory: false}
1: {id: 281, name: "Zone", mandatory: false}
2: {id: 284, name: "City", mandatory: true}
3: {id: 272, name: "Building", mandatory: true}
4: {id: 292, name: "Street", mandatory: true}

<div *ngFor="let countryData of countryDetailsArray;">
    <div>
        <button>
            {{countryData.name}}
        </button>
    </div>
</div>

Solution

  • I wouldnt try to do that in the HTML it would be much better to do it in the .ts file as a function that returns a new array which has the two elements you want. the function would look something like this:

    countryDetailsArray = [
    {id: 278, name: "State", mandatory: false},
    {id: 281, name: "Zone", mandatory: false},
    {id: 284, name: "City", mandatory: true},
    {id: 272, name: "Building", mandatory: true},
    {id: 292, name: "Street", mandatory: true},
    ]
    
    getFirstOfEach() {
      let array = []
      array.push(this.countryDetailsArray.find(item => item.mandatory === false));
      array.push(this.countryDetailsArray.find(item => item.mandatory === true));
      return array
    }