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