* ngFor数组动态字符串插值
问题描述:
其实我有我想动态改变数组循环的情况。* ngFor数组动态字符串插值
export interface City {
street: Street[];
country: Country[];
}
<div>
<div (click)="OnClick()">Street</div>
<div (click)="OnClick()">Country</div>
</div>
<div *ngIf="clicked">
<div *ngFor="let c of city.street">
<div>
{{c.name}}
</div>
</div>
</div>
如果用户点击街道,街道的值应循环。
预期:* ngFor = “让city.street的C”
如果全国用户点击,这个国家的价值观应该循环。
预期:* ngFor =
我曾尝试以下 “让city.country的C”:
<div>
<div (click)="OnClick('street')">Street</div>
<div (click)="OnClick('country')">Country</div>
</div>
<div *ngIf="clicked">
//Porperty Binding
<div *ngFor="let c of city.{{onClickParameter}}">
<div>
{{c.name}}
</div>
</div>
</div>
它doenst工作(模板解析错误,因为城市{{ }}) 是否有解决方案?
答
可以使用组件的函数来处理它:
//Component
export interface City {
street: Street[];
country: Country[];
}
export class MyComponent {
public selected : string = 'street';
public city: City;
OnClick(select: string) {
this.selected = select;
}
}
// You HTML
<div>
<div (click)="OnClick('street')">Street</div>
<div (click)="OnClick('country')">Country</div>
</div>
<div *ngIf="clicked">
<div *ngFor="let c of city[selected]">
<div>{{c.name}}</div>
</div>
</div>
你可以通过移动'城市进一步简化模板[所选]'成使用例如类一个属性'get listOfThings(){return this.city [this.selected]; }' – jonrsharpe
这对我有效..我喜欢.. thx – mimu1011