[英]Angular *ngFor Data Matching
我需要幫助以找到在Angular 7模板中顯示JSON數據的正確方法。 如您在下面的JSON示例中所看到的,我有一個帶有多個標識號的person對象,我正在使用* ngFor在模板中顯示它們,並使用* ngIf來匹配類型並顯示數字。 但是,此方法只會顯示有數據可用的字段,如果未從JSON對象返回學生ID,則不會顯示包括標簽的整個字段。
我的第一件事是,我是否通過使用* ngIf匹配ngFor中的id類型來做正確的事情?
其次,還有另一種方法來表示標識數據,如果id類型不可用,例如未返回studentID類型,則可以使用模板顯示N / A?
*更新重復護照錯誤
JSON數據樣本
person = {
name: { firstname: "John ", lastname: "Smith" },
identification: [
{ type: "ID", number: "CSG112345", },
{ type: "PASSPORT", number: "AB4455566" }
]}
模板
<ng-container *ngFor="let id of person.identification">
<p *ngIf="id.type==='ID'">
<label>ID:</label>
<b>{{id.number}}</b>
</p>
<p *ngIf="id.type==='PASSPORT'" >
<label>Passport Number :</label>
<b>{{id.number}}</b>
</p>
<p *ngIf="id.type==='STUDENTID'">
<label>Student Number :</label>
<b>{{id.number}}</b>
</p>
</ng-container>
* ngIfs不正確。 只是ngSwitch更干凈。 您可以在模板中使用三元運算符來設置默認值。
<ng-container *ngFor="let id of person.identification">
<ng-container [ngSwitch]="id.type">
<p *ngSwitchCase="'PASSPORT'">
<label>Passport :</label>
<b>{{id.number ? id.number : 'N/A'}}</b>
</p>
<p *ngSwitchCase="'PASSPORT'">
<label>Passport Number :</label>
<b>{{id.number ? id.number : 'N/A'}}</b>
</p>
<p *ngSwitchCase="'STUDENTID'">
<label>Student Number :</label>
<b>{{id.number ? id.number : 'N/A'}}</b>
</p>
</ng-container>
</ng-container>
另外,您有PASSPORT的副本。 不知道這是否是故意的。 由於我們正在迭代數組到模板,因此在顯示模板之前,應為不存在的成員提供默認值。 那是我的方法。 否則,您需要像
checkForType(type:string):boolean{
return person.identification.map(e => e.type).includes(type)
};
並在模板中檢查它。 就像是
<ng-container *ngIf="checkForType(id.type)">
.....
</ng-container>
<ng-container *ngIf="!checkForType(id.type)">
.....
</ng-container>
但這會導致html文件膨脹。 我建議您在將其呈現到html之前為其提供默認值。
<b>{{id.number ? id.number : 'N/A'}}</b>
只需使用此行代替<b>{{id.number}}</b>
您將獲得預期的輸出。
如果要顯示每個模板元素,只需在<b>
本身中添加條件。 請參閱更新的stackblitz。 https://stackblitz.com/edit/angular-tqixcb
<p>
<label>Name :</label>
<b>{{person.name.firstname}}</b>
</p>
<p>
<label>ID :</label>
<b>{{getNumber("ID")}}</b>
</p>
<p>
<label>Passport Number :</label>
<b>{{getNumber("PASSPORT")}}</b>
</p>
ts方法:
getNumber(type): String {
const numberValue = this.person.identification.find(x => x.type === type);
if(!numberValue) {
return "N/A"
}
return numberValue.number;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.