我对角度很陌生,我确信这是一个非常基本的问题,但我想显示一个与特定SymptomID相匹配的症状列表。我有下面的代码,它检查特定症状是否属于特定类型,但是当类型不正确时,代码仍然输出一个空白符号。
<h1>Symptoms</h1>
<h2> {{symptomtypes[0].Description}}</h2>
<li *ngFor="let symptom of symptoms">
<p *ngIf="(symptom.SymptomTypeID == 1)"> {{symptom.Description}}</p>
</li>
<h2> {{symptomtypes[1].Description}}</h2>
<li *ngFor="let symptom of symptoms">
<p *ngIf="(symptom.SymptomTypeID == 2)"> {{symptom.Description}}</p>
</li>
<h2> {{symptomtypes[2].Description}}</h2>
<li *ngFor="let symptom of symptoms">
<p *ngIf="(symptom.SymptomTypeID == 3)"> {{symptom.Description}}</p>
</li>
我期望该列表的输出如下:
症状1型
症状2型
症状3型
但我却得到了这样的东西:
症状1型
症状2型
症状3型
发布于 2019-05-21 11:55:17
我想你要找的解决办法是。
<h1>Symptoms</h1>
<h2> Symptom Type 1</h2>
<div *ngFor="let symptom of symptoms">
<li *ngIf="(symptom.SymptomTypeID == 1)&& (symptom.Description)">
{{symptom.Description}}
</li>
</div>
<h2> Symptom Type 2</h2>
<div *ngFor="let symptom of symptoms">
<li *ngIf="(symptom.SymptomTypeID == 2)&& (symptom.Description)">
{{symptom.Description}}
</li>
</div>
<h2> Symptom Type 3</h2>
<div *ngFor="let symptom of symptoms">
<li *ngIf="(symptom.SymptomTypeID == 3) && (symptom.Description)">
{{symptom.Description}}
</li>
</div>
发布于 2019-05-21 11:46:34
您的代码不是显示值的理想方法,而是用于这种特殊情况。我想你要找的解决办法是。
<h2> {{symptomtypes[2].Description}}</h2>
<li *ngFor="let symptom of symptoms">
<p *ngIf="(symptom.SymptomTypeID == 3) && symptom.Description"> {{symptom.Description}}</p>
</li>
发布于 2019-05-21 11:47:42
您需要知道,*ngFor
的每一次迭代都创建了应用*ngFor
的html元素(参见文档)。正因为如此,您才有空条目。
在您的情况下,我建议您使用管道来筛选数组。
@Pipe({ name: 'filterSymptom' })
export class FilterSymptomPipe implements PipeTransform {
transform(symptoms: Symptom[], id: number) {
return symptoms.filter(s => s.SymptomTypeID === id);
}
}
在你的html中:
<li *ngFor="let symptom of symptoms | filterSymptom: 3">
<p"> {{symptom.Description}}</p>
</li>
为了改进您的代码,我建议您执行以下操作:
<ng-template *ngFor="let symptomtype of symptomtypes; let index=index;">
<h2> {{symptomtype.Description}}</h2>
<li *ngFor="let symptom of symptoms | filterSymptom: index + 1]">
<p"> {{symptom.Description}}</p>
</li>
</ng-template>
这样可以防止硬编码索引的使用。
https://stackoverflow.com/questions/56245269
复制相似问题