angular - 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 值。
解决方案
零件:
public foo: string;
setNewValue(newValue) {
this.foo = newValue;
}
模板:
<input [(ngModel)]="foo" class="form-control" placeholder="{{'referenceNo' | translate}}">
public
基本上,您将如何做您想做的是将类属性(如果使用 AOT,则必须是)绑定到ngModel
指令,用户键入对属性的任何更改都将反映在组件中,因为它是使用“双向绑定”的[()]
句法。您可以进行一次绑定,[ngModel]="foo"
但在您的场景中您不希望这样做。
我建议阅读有关如何ngModel
工作的内容,并查看使用FormBuilder
. 通常在处理表单时,它更强大、更容易使用。
推荐阅读
- python - QGIS中第二个坐标中的相同随机值如何排列?
- docker - 连接失败。Docker 正在运行吗?
- c++ - 如何将 nlohmann 二进制转换为 uint8_t 向量?
- python-3.x - 使用python获取每个进程的名称和CPU利用率
- nginx - nginx 处理涉及上游代理的请求所花费的记录时间
- javascript - 如何使用 S3 预签名的 POST url?
- arrays - scanf 与数组,何时添加 & 何时不添加 &
- c# - 下载多个文件,因为 zip 引发了“System.NotSupportedException”类型的异常
- google-api - Google 企业 (G Suite) 帐户是否有租户 ID 或等效项来区分租户?
- r - 在 R 中创建一个空数据框,列名存储在两个单独的列表中