1

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
  }
2
  • 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. Commented Jan 31, 2018 at 21:58
  • 2
    your code works fine: plnkr.co/edit/wHbpbQkEcyvAGafHC3bN?p=preview Commented Jan 31, 2018 at 22:12

3 Answers 3

7

You can use attr prefix with attributes something like below

[attr.name]="col.header"
Sign up to request clarification or add additional context in comments.

Comments

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);
  }

Comments

-4

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'}}"

2 Comments

all three are invalid if you want to set name attribute
use [attr.name]="col.header"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.