简体   繁体   English

setAttribute将无法与ngModel一起使用

[英]setAttribute won't work with ngModel in angular

i'm trying to auto assign ngModel while creating a html element This is my code, 我正在尝试在创建html元素时自动分配ngModel这是我的代码,

productName.setAttribute('[(ngModel)]', `customProductName`);

But i keep getting this error, 但是我不断收到这个错误,

Failed to execute 'setAttribute' on 'Element': '[(ngModel)]' is not a valid attribute name.

other html attributes work fine. 其他html属性工作正常。 Please how can i go about this, thank you. 请我该怎么做,谢谢。

I haven't set value of ngModel as you have done, but i could suggest, the simplest solution for setting custom model value is as below, 我没有像您那样设置ngModel的值,但是我建议,设置自定义模型值的最简单解决方案如下,

create a model interface like, 创建一个model界面,例如

productModel.ts productModel.ts

export interface ProductModel {
    productName: string;
}

And in your template, 在您的模板中

product.component.html product.component.html

if it is input tag, 如果是输入标签,

// other code form code here        

<input type="text" name="productName" id="productName" placeholder="Your productName" [(ngModel)]="model.productName">

// more code here

In component, 在组件中

product.component.ts 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';
}

Please let me know if this solution is useful or not.. thanks 请让我知道此解决方案是否有用..谢谢

Note: This is Template driven form example u can achieve this even with Reactive forms also 注意:这是模板驱动的表单示例,即使使用Reactive表单,您也可以实现此目的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM