首页 > 解决方案 > Angular 2 ViewChild NgModel 设置新值

问题描述

<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)
}

还尝试从元素 ref 更改值。

@ViewChild(forwardRef(() => NgForm)) form: NgForm;

for (let elRef of this.form.element.nativeElement) {
  elRef.value = "New Value" // Doesnt change value
}

请帮助我需要从组件类中操作我的表单 inut 值。

标签: angular

解决方案


零件:

public foo: string;

setNewValue(newValue) {
  this.foo = newValue;
}

模板:

<input [(ngModel)]="foo" class="form-control" placeholder="{{'referenceNo' | translate}}">

public基本上,您将如何做您想做的是将类属性(如果使用 AOT,则必须是)绑定到ngModel指令,用户键入对属性的任何更改都将反映在组件中,因为它是使用“双向绑定”的[()]句法。您可以进行一次绑定,[ngModel]="foo"但在您的场景中您不希望这样做。

我建议阅读有关如何ngModel工作的内容,并查看使用FormBuilder. 通常在处理表单时,它更强大、更容易使用。


推荐阅读