Need to filter some data from Array in Angular while traversing with *ngFor
我有一个包含一些对象元素的数组。从下面的数组中,我想获得第一个具有 "mandatory: false" 的对象和第一个具有 "mandatory: true" 的元素。
从下面的列表中,我需要在 UI 中获取state和城市。
1 2 3 4 5 6 7 8 9 10 11 12 | 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} <button> {{countryData.name}} </button> |
我不会尝试在 HTML 中执行此操作,最好在 .ts 文件中作为一个函数执行此操作,该函数返回一个包含您想要的两个元素的新数组。该函数看起来像这样:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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 } |