2017-03-18 68 views
6

我正在試驗Angular2和Angular Material。我用*ngFor讓Angular爲我生成了<input>元素。但是,在生成的網頁中,生成的元素不具有name屬性。Angular2綁定的「名稱」屬性<input>元素* ngFor

這是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瀏覽器,當我右擊'蘋果'<input>,該元素的屬性name是空的,但ng-reflect-name設置爲​​正確?如何解決這個問題? No name attribute here, but ng-reflect-name is apples

+0

你會得到任何錯誤? – Aravind

+0

@Aravind從下面的控制檯,沒有錯誤。 –

回答

9

最終答案

使用([name]="fruit"name="{{fruit}}")和([attr.name]="fruit"attr.name="{{fruit}}")一起將工作。

更新

如果你想使用字符串'fruit'作爲name屬性值,使用

name="fruit" 

name="{{'fruit'}}" 

或 [名] =「」水果'「

否則你綁定組件領域fruit(你的分量似乎不有)的

角也財產默認綁定的值。如果你想綁定的屬性,你需要做的是明確

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

[name]="fruit" 

參見

+0

當我使用'attr。name =「{{fruit}}」'瀏覽器會給我一個錯誤:如果ngModel在表單標籤中使用,則必須設置name屬性或者必須在ngModelOptions中將表單控件定義爲'standalone'。當我使用'[name] =「fruit」時,結果根本不會改變。 –

+0

然後問題是別的。所以你實際上並不關心被添加到''的'name'屬性,你只是想讓'ngModel'工作? –

+0

我想你實際上想'name =「水果」' –