【问题标题】:How to set dynamic id in *ngFor?如何在 *ngFor 中设置动态 id?
【发布时间】:2016-04-06 17:29:03
【问题描述】:

如何在Angular 2中设置动态id

我试过了:

<div class = "CirclePoint" *ngFor="#c of circles" id = "{{ 'Location' + c.id }}"></div>

this.circles = [
        { x: 50 , y: 50 ,id : "oyut1" },
        { x: 100 , y: 100 ,id : "oyut3"  },
        { x: 150 , y: 150 ,id : "oyut2"  }
];

但它不起作用。

【问题讨论】:

    标签: angular ionic2


    【解决方案1】:
    <div class = "CirclePoint" *ngFor="let c of circles" 
        [attr.id]="'Location' + c.id">
    </div>
    
    <div class = "CirclePoint" *ngFor="let c of circles" 
        attr.id="Location{{c.id}}">
    </div>
    

    对于id 属性,这可能也有效(我自己还没试过)

    <div class = "CirclePoint" *ngFor="let c of circles" 
    [id]="'Location' + c.id">
    </div>
    

    【讨论】:

    • 感谢您的反馈,我以为有一些特殊处理的共同属性,但也许我弄混了。
    【解决方案2】:

    这也可以:

    <div class = "CirclePoint" *ngFor="let c of circles">
       <div [id]="c.id"></div>
    </div>
    

    如果要添加前缀,请说“loc”;

    <div class = "CirclePoint" *ngFor="let c of circles">
       <div [id]="'loc' + c.id"></div>
    </div>
    

    使用 [] 有助于动态添加值。

    【讨论】:

      【解决方案3】:

      试试这个:

       <div class = "CirclePoint" *ngFor="let c of circles">
           <div id="location_{{c.id}}">write something which you want like c.x </div>
       </div>`
      

      希望这对您有用。我搜索了 StackOverflow,发现了这个 answer

      【讨论】:

      • 感谢您的回答。但我正在研究 angular2 “ng-attr-id” 不再起作用了。
      • 对不起,没有看到标签,我不能在 angular2 中工作,我回复你。我从网上找到了一些答案
      【解决方案4】:

      在组件标签中,而不是通常的id="#c" 使用[id]="#c"。这也适用于动态类名。请参见下面的示例:

      <div class = "CirlePoit" *ngFor="#c of circles" [id] = "#c"> </div>
      

      【讨论】:

        【解决方案5】:

        索引可以用作动态 ID

        <div class="test" *ngFor="let item of data; let i = index">
        <div class="function_div" (click)="test(i);">Test Button </div>
            {{item}}
        </div>
        

        【讨论】:

          猜你喜欢
          • 2017-06-09
          • 2018-03-09
          • 2023-01-30
          • 2017-11-16
          • 1970-01-01
          • 2015-12-20
          • 2018-06-26
          • 1970-01-01
          • 2016-09-10
          相关资源
          最近更新 更多