0

I am trying to dynamically set the name attribute to my input fields I have in a data table in Angular inside of an *ngFor. However, I am seeing when I go to console.log the event of in my filter method on keyup in the fields, there is no name being set for each input. How do add these names dynamically?

table.component.html

<table>
    <thead>
        <tr>
            <th *ngFor="let col of cols" 
            (click)="selectColHeader(col.prop); 
            col.enableSort && sort(col.prop)"
            role="button">
                <label>{{col.header}}</label>
                <input type="text"
                aria-label="search text field"
                name="{{col.header}}" <-- not being set
                ngModel
                placeholder="search..."
                (click)="$event.stopPropagation()"
                (keyup)="filterData($event)"
                *ngIf=col.enableFilter/>
            </th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor="let row of data |
        filter: fields:selectedInput |
        paginate: { itemsPerPage: 6, currentPage: page, id: id }">
            <td *ngFor="let col of cols">
                {{row[col.prop]}}
            </td>
        </tr>
    </tbody>
</table>

table.component.ts

  filterData(e){
    console.log(e.target.name) <--- name is a blank string 
    console.log(e)
    this.fields = e.target.value
  }
FakeEmpire
  • 668
  • 1
  • 14
  • 35
  • 2
    There's nothing wrong with your code. I copied it and it worked for me. This suggests that the issue is with col.header. Perhaps it doesn't have a value. try changing the click event to pass in the col object and console log to check to see if the header has a value. – David Anthony Acosta Jan 31 '18 at 21:58
  • 2
    your code works fine: https://plnkr.co/edit/wHbpbQkEcyvAGafHC3bN?p=preview – Zze Jan 31 '18 at 22:12

3 Answers3

6

You can use attr prefix with attributes something like below

[attr.name]="col.header"
Vikas Kandari
  • 1,612
  • 18
  • 23
1

I would suggest using a "formControlName":

Component.html File:

<input [formControlName]="q.sFieldName" [id]="q.sFieldName" class="form-control m-input">

component.ts File:

  form: FormGroup;
  payLoad = '';

  onSubmit() {
    this.payLoad = JSON.stringify(this.form.value);
  }
-3

Angular2 binding of "name" attribute in <input> elements with *ngFor

Basically name="{{col.header}}" is not correct syntax.

These are:

  1. name="col.header"

  2. [name]="'col.header'"

  3. name="{{'col.header'}}"

Mark
  • 139
  • 7