簡體   English   中英

Angular 2 ViewChild NgModel 設置新值

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM