[英]Angular 2 ViewChild NgModel Set New Value
<input type="text" class="form-control" name="referenceNo/LIKE" placeholder="{{'referenceNo' | translate}}" ngModel>
@ViewChildren(forwardRef(() => NgModel)) inputs: QueryList<NgModel>;
for (let input of this.inputs.toArray()) {
//change value input(NgModel Ref)
}
還嘗試從元素引用更改值。
@ViewChild(forwardRef(() => NgForm)) form: NgForm;
for (let elRef of this.form.element.nativeElement) {
elRef.value = "New Value" // Doesnt change value
}
請幫助我需要從組件類操作我的表單輸入值。
成分:
public foo: string;
setNewValue(newValue) {
this.foo = newValue;
}
模板:
<input [(ngModel)]="foo" class="form-control" placeholder="{{'referenceNo' | translate}}">
基本上,您將如何做您想做的事情是將類屬性(如果使用 AOT 則必須是public
)綁定到ngModel
指令,用戶鍵入對屬性的任何更改都將反映在組件中,因為它是“雙向綁定”使用[()]
語法。 一次綁定你可以做[ngModel]="foo"
但在你的場景中你不想要那樣。
我建議閱讀有關ngModel
工作原理,並使用FormBuilder
看看反應式FormBuilder
。 通常在使用表單時,它更強大且更易於使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.