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

时间:2018-01-31 21:47:48

标签: javascript angular

我正在尝试将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
  }

3 个答案:

答案 0 :(得分:1)

我建议使用“ formControlName”:

Component.html文件:

export class PaypalComponent implements OnInit {
  paypalConfig = {
    env: 'sandbox',
    client: {
      sandbox: 'ATvgtyEZznsHf...',
      production: '<insert production client id>'
    },
    style: {
      layout: 'vertical',
      label: 'pay',
      size: 'responsive',
      shape: 'rect',
      color: 'gold'
    },
    commit: true,
    payment: (data, actions) => {
      return actions.payment.create({
        payment: {
          transactions: [{
            amount: {
              total: 10.5,
              currency: "EUR",
            }
          }]
        }
      });
    },
    onAuthorize: (data, actions) => {
      return actions.payment.execute().then((response) => {
        console.log('response', response);
        console.log('data', data);
        console.log('actions', actions);
      });
    },
    onCancel: (data, actions) => {
      console.log('Canceled!');
    }
  };

  ngOnInit() {
    paypal.Button.render(this.paypalConfig, '#payments-container');
  }
}

component.ts文件:

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

答案 1 :(得分:1)

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

[attr.name]="col.header"

答案 2 :(得分:-1)

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