3

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

dragonmnl
  • 14,578
  • 33
  • 84
  • 129

1 Answers1

2

>=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;
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567