【问题标题】:*ngFor dynamic string interpolation with array*ngFor 动态字符串插值与数组
【发布时间】:2017-03-23 03:27:53
【问题描述】:

实际上我有一种情况,我想动态改变数组循环。

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="let c of city.street"

如果用户点击国家,国家的值应该循环。

预期:*ngFor="let c of city.country"

我尝试了以下方法:

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

它确实有效(Template Parse Error because city.{{}}) 还有其他解决方案吗?

【问题讨论】:

    标签: javascript angular typescript ngfor


    【解决方案1】:

    你可以使用组件函数来处理它:

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

    【讨论】:

    • 您可以通过将city[selected] 移动到类中来进一步简化模板,例如属性get listOfThings() { return this.city[this.selected]; }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-01
    • 2011-10-19
    • 1970-01-01
    • 2020-07-31
    • 2012-11-13
    • 1970-01-01
    相关资源
    最近更新 更多