<input> 元素中 "name" 属性与 *ngFor 的 Angular2 绑定

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

我正在试验 Angular2 和 Angular Material。我使用 *ngFor 让 Angular 为我生成 <input> 元素。但是,在生成的网页中,生成的元素没有 name 属性。

这是order-form.component.html中的部分代码,它要求用户输入不同种类水果的数量:

<md-list-item>
  <md-icon md-list-icon>shopping_cart</md-icon>
  <md-input-container *ngFor="let fruit of fruits" class="fruit-input">
    <input mdInput [(ngModel)]="order[fruit]" [placeholder]="capitalize(fruit)" 
           [id]="fruit" name="{{fruit}}" required value="0" #fruitInput 
           (input)="onInput(fruitInput)">
  </md-input-container>
</md-list-item>

这是对应的order-form.component.ts:

import { Component, OnInit } from "@angular/core";
import { Order } from "app/order";
import { PAYMENTS } from "app/payments";
import { OrderService } from "app/order.service";

@Component({
  selector: 'app-order-form',
  templateUrl: './order-form.component.html',
  styleUrls: ['./order-form.component.css']
})
export class OrderFormComponent implements OnInit {

  order = new Order();

  payments = PAYMENTS;

  fruits: string[] = [
    'apples',
    'oranges',
    'bananas'
  ];

  constructor(public service: OrderService) {
  }

  ngOnInit() {
  }

  get totalCost() {
    return this.service.getTotalCost(this.order);
  }

  onFocus(element: HTMLElement) {
    element.blur();
  }

  onSubmit() {
    console.log('onSubmit');
  }

  onInput(element: HTMLInputElement) {
    console.log(element);
    if (!this.service.isValidIntString(element.value)) {
      window.alert(`Please input a correct number for ${element.name}`);
      element.value = '0';
    }
  }

  capitalize(str: string): string {
    return this.service.capitalize(str);
  }

  get debug() {
    return JSON.stringify(this.order, null, 2);
  }
}

在Chrome浏览器中,当我右击'apples'<input>时,元素的name属性为空,但是ng-reflect-name是否正确设置为 apples?如何解决这个问题? No name attribute here, but ng-reflect-name is apples

最终答案

同时使用 ([name]="fruit"name="{{fruit}}") 和 ([attr.name]="fruit"attr.name="{{fruit}}") 会有效。

更新

如果要使用字符串 'fruit' 作为 name 属性的值,请使用

name="fruit"

name="{{'fruit'}}"

[name]="'fruit'"

否则你绑定组件字段的值fruit(你的组件似乎没有)

原创

Angular 默认进行 属性 绑定。如果你想要属性绑定,你需要明确

 attr.name="{{fruit}}" (for strings only)

 [name]="fruit"

另见

  • What is the difference between attribute and property?