2017-01-03 70 views
0

我試圖設置一個表單,管理員用戶可以設置氣瓶的價格。一瓶有一個類型,名稱,價格如下:Angular2:無法獲取NGFFor在ngForm中重複輸入的輸入值

export class Bottle { 

    constructor(
    public typeId: string, 
    public name: string, 
    public price: number 
) 
    { } 
} 

這裏顯示的形式:一個帳戶ID輸入,並與ngFor重複瓶子的列表。

<form (ngSubmit)="onSubmit()" #bottleUpdatePriceForm="ngForm" > 

    <div class="form-group"> 
     <label for="accountId ">Account ID : </label> 
     <input type="text" class="form-control" id="accoundId" name="accountId" required [(ngModel)]="accountId"> 
    </div> 

    <div class="form-group" *ngFor="let bottle of bottleArrayToUpdate; let i = index"> 
     <label for="bottlePrice ">{{bottle.name}} : </label> 
     <input type="text" class="form-control" id="bottlePrice" name="bottlePrice" [ngModel]="bottleArrayToUpdate[i].price"> 
    </div> 

    <button type="submit" class="btn btn-default">Submit</button> 
    </form> 

我從另一個組件作爲瓶(6實際上),他們的類型名稱設置陣列發送數據到我的形式,並且其中價格爲空。

@Input() private bottleArrayToUpdate: Bottle[]; 

... 

onSubmit() { 
    this.submitted = true;  

    console.log(this.accountId); // => Works fine 
    console.log(this.bottleArrayToUpdate); // => All the prices are still null 
} 

有沒有辦法讓瓶子的重複輸入的輸入值和標準形式,而不是反應形式?

我也試過[ngModel]="bottle.price但我無法訪問我的值。

感謝您的幫助

+0

此外,可能是一個可能的重複,但我沒有找到答案在其他職位,因此我的問題。 –

回答

1

您應該使用[()]記號,以確保雙向綁定:

<input type="text" name="bottlePrice" [(ngModel)]="bottle.price"> 

也不要使用id,因爲這應該是在頁面上獨一無二的,你是使用它在一個*ngFor :)

+0

哦,我的上帝,我想知道爲什麼這不起作用......沒有奇蹟......我覺得真的很愚蠢。 非常感謝! (和好的提示以及) –

+0

我想到了很多:),因爲你確實在'accoundId' – PierreDuc