How to set bindings in ngFor in Angular 2?

£可爱£侵袭症+ 提交于 2019-12-10 22:23:22

问题


NOTE: I found several similar questions but none really answered my (generic) question

I have this

component.ts

first: string;
second: string;
third: string;
fields = ["first", "second", "third"];

I want to be able to generate in component.html a complex component (without importing a custom-defined directive) which includes:

  • Required: ngModel binding based on fields[i]

    (e.g. i = 0, fields[i] = "first", ngModel = first)

  • Desiderable: use fields[i] as strings to assign to any DOM element property (e.g.

The loop looks like this:

 <div *ngFor="let field of fields">
      <label for="???>
      [(ngModel)]="???"
 </div>

As for the 2nd point, it works with id and as content of the div.

However...

  • in the case of ngModel: [(ngModel)] = "field" leads to an exception (Cannot assign to a reference or variable!)
  • in the case of assigning a string to (for example)

     <label for="{{field}}">,
    

    I get an exception as well (Can't bind to 'for' since it isn't a known native property (" i">)


回答1:


>=RC.6

 <label for="{{field}}">
 <label [for]="field">

<=RC.5

 <label attr.for="{{field}}">
 <label [attr.for]="field">
 <label [htmlFor]="field">

update

<div *ngFor="let field of fields; let i=index; trackBy:trackByIndex">
  <label htmlFor="field">
  <input [(ngModel)]="fields[i]">
</div>

and add this to the component

trackByIndex(index: number, obj: any): any {
  return index;
}


来源:https://stackoverflow.com/questions/39347773/how-to-set-bindings-in-ngfor-in-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!