Mo_Code Mo_Code - 23 days ago 15
TypeScript Question

*ngFor dynamic string interpolation with array

Actually i have the situation that i want to change the array looping dynamically.

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>


If the User click on Street, the Values of the street should loop.


expected: *ngFor="let c of city.street"


If the user click on country, the values of the country should loop.


expected: *ngFor="let c of city.country"


I have tried the following:

<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>


It doenst work ( Template Parse Error because city.{{}} )
Is thereother solutions ?

Answer

You can use component function to handle it:

//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>
Comments