【问题标题】:Dynamically set name attribute to input field in Angular动态地将名称属性设置为Angular中的输入字段
【发布时间】:2018-07-11 03:26:12
【问题描述】:

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

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
  }

【问题讨论】:

  • 您的代码没有问题。我复制了它,它对我有用。这表明问题出在 col.header 上。也许它没有价值。尝试更改单击事件以传入 col 对象和控制台日志以检查标题是否有值。

标签: javascript angular


【解决方案1】:

您可以将 attr 前缀与下面的属性一起使用

[attr.name]="col.header"

【讨论】:

    【解决方案2】:

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

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

    这些是:

    1. name="col.header"

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

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

    【讨论】:

    • 设置name属性三个都无效
    • 使用 [attr.name]="col.header"
    【解决方案3】:

    我建议使用“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);
      }
    

    【讨论】:

      猜你喜欢
      • 2020-12-13
      • 2015-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多