【问题标题】:Accessing specific array based on key in ngFor根据 ngFor 中的键访问特定数组
【发布时间】:2017-12-05 03:29:09
【问题描述】:
<button *ngFor="let item of items[category]"> </button>

在哪里items: { cat1: [], cat2: [] }。 我需要 category 作为字符串变量来访问项目中的两个数组。 我该如何解决这个问题?

【问题讨论】:

    标签: angular ngfor


    【解决方案1】:

    试试这个:

    //our root app component
    import {Component, NgModule, VERSION} from '@angular/core'
    import {BrowserModule} from '@angular/platform-browser'
    
    @Component({
      selector: 'my-app',
      template: `
        <div>
             <button *ngFor="let item of items[category]" > {{item}}</button>
        </div>
      `,
    })
    export class App {
      items: any =  { cat1: ['cat1','cat2'], cat2: ['peter','peter2'] };
      category = 'cat1';
      constructor() {
      }
    }
    
    @NgModule({
      imports: [ BrowserModule ],
      declarations: [ App ],
      bootstrap: [ App ]
    })
    export class AppModule {}
    

    plunkr 工作:

    https://plnkr.co/edit/w1YJeZPAMwN5WP3uVhZ7

    【讨论】:

    • 我正在使用你正在做的事情,但我的钥匙是“猫”,我正在尝试使用“猫”,但我不知道到底出了什么问题!无论如何我会接受你的回答,因为它是正确的。
    猜你喜欢
    • 2021-03-05
    • 1970-01-01
    • 2021-07-22
    • 2017-04-30
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 2022-10-21
    • 1970-01-01
    相关资源
    最近更新 更多