[英]setAttribute won't work with ngModel in angular
我正在尝试在创建html元素时自动分配ngModel这是我的代码,
productName.setAttribute('[(ngModel)]', `customProductName`);
但是我不断收到这个错误,
Failed to execute 'setAttribute' on 'Element': '[(ngModel)]' is not a valid attribute name.
其他html属性工作正常。 请我该怎么做,谢谢。
我没有像您那样设置ngModel的值,但是我建议,设置自定义模型值的最简单解决方案如下,
创建一个model
界面,例如
productModel.ts
export interface ProductModel {
productName: string;
}
在您的模板中
product.component.html
如果是输入标签,
// other code form code here
<input type="text" name="productName" id="productName" placeholder="Your productName" [(ngModel)]="model.productName">
// more code here
在组件中
product.component.ts
// create an instance of ProductModel instance by name variable model
model: ProductModel = new ProductModel();
// set the product name with custom value as below on ngOninit fuction
ngOninit () {
this.model.productName = 'Custom product Name';
}
请让我知道此解决方案是否有用..谢谢
注意:这是模板驱动的表单示例,即使使用Reactive表单,您也可以实现此目的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.