首页 文章

在Angular中将name属性动态设置为输入字段

提问于
浏览
0

我试图动态地将name属性设置为我在* ngFor内的Angular数据表中的输入字段 . 但是,我看到当我在console.log中输入字段中keyup的filter方法中的事件时,没有为每个输入设置名称 . 如何动态添加这些名称?

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 回答

  • -1

    我建议使用“formControlName”:

    Component.html文件:

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

    component.ts文件:

    form: FormGroup;
      payLoad = '';
    
      onSubmit() {
        this.payLoad = JSON.stringify(this.form.value);
      }
    
  • 1

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

    基本上 name="{{col.header}}" 语法不正确 .

    这些是:

    • name="col.header"

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

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

相关问题