2016-06-11 76 views
2

这是我的代码:Angular 2 | NgformControl阻止我NgModel从更新

HTML:

<div *ngFor="let reject of rejects, let i = index"> 
    <h2>{{reject.reason}}</h2> 
    <input type="text" [(ngModel)]="reject.reason" [ngFormControl]="inputField"> 
    <rt-dropdown (selectedReason)="selectReason($event.value, i)"></rt-dropdown> 
</div> 

和我mainTS:当你点击一个原因

class { 
    inputField = new Control(); 


    constructor(private _broadcastService : BroadcastService) { 
     this.inputField.valueChanges 
      .debounceTime(300) 
      .subscribe(term => this._dropdownComponent.query(term)); 
    } 
} 



selectReason(text, index) { 
this.rejects[index].reason = text; 
} 

RT-下拉只发送一个理由。

问题是,当您单击某个原因时,{{reject.reason}}会更改,但输入字段不会更改。

这就像网页没有更新,任何人都可以在此体验?

谢谢

+0

它看起来像最终为单个组件的2个FormControl实例。也许你应该删除ngFormControl绑定并使用'@VidewChild(“input”)input:NgFormControl'在你的控制器中注入它,而不是实例化一个新的。 – cghislai

+0

我跟着Gunter Zochbauers回答每次重复做一次控制(只需要5次,所以效果很好!)无论如何,谢谢! –

回答

1
<div *ngFor="let reject of rejects let idx=index"> 
    <h2>{{reject.reason}}</h2> 
    <input type="text" [(ngModel)]="rejects[idx].reason" [ngFormControl]="inputField"> 
    <rt-dropdown (selectedReason)="selectReason($event.value, i)"></rt-dropdown> 
</div> 

您还需要尽可能多的inputField = new Control()(也许一的inputFields数组,你有条目rejects和引用它们

[ngFormControl]="inputFields[idx]" 

否则所有输入要素指的是同一Control实例。

+0

是的,这可能是问题,但我如何制作一组控制对象?就像inputFields = new Control()[]?以某种方式给出错误.. –

+0

我没有看到你的'rejects'数组是如何构建的。你可以用'inputFields:Control [] = [];' –

+1

'来实现'this.rejects.forEach(r => this.inputFields.push(new Control())''你是一个Angular Genius!非常感谢第二个时间 ! –

1

我想尝试,而不是执行以下操作:

<div *ngFor="let reject of rejects, let i = index"> 
    (...) 
    <input type="text" [(ngModel)]="rejects[i].reason" 
     [ngFormControl]="inputField"> 
</div> 

编辑

我会用一个控件数组为相应的控件:

let inputFieldControls = new ControlArray([]); 

for(let i = 0 ; (...) ; i++){ 
    inputFieldControls.push(new Control('' , Validators.required)); 
} 

和以这种方式使用它:

<div *ngFor="let reject of rejects, let i = index"> 
    (...) 
    <input type="text" [(ngModel)]="rejects[i].reason" 
     [ngFormControl]="inputFieldControls[i]"> 
</div> 
+0

这不起作用,它只是相同 –

+0

你可以尝试使用控件数组作为控件。我相应地更新了我的答案...... –