【问题标题】:setAttribute won't work with ngModel in angularsetAttribute 不适用于 ngModel 角度
【发布时间】:2018-12-14 12:04:04
【问题描述】:

我正在尝试在创建 html 元素时自动分配 ngModel 这是我的代码,

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

但我不断收到此错误,

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

其他 html 属性工作正常。请问我该怎么办呢,谢谢。

【问题讨论】:

  • 欢迎使用 Stack Overflow,您介意在 plunk 或 stackblitz 上分享您的代码,以便其他人可以帮助您吗?还介绍了如何创建最小、完整和可验证的示例

标签: javascript html node.js angular angular6


【解决方案1】:

我没有像你那样设置 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';
}

请让我知道这个解决方案是否有用。谢谢

注意:这是模板驱动的表单示例,你甚至可以实现这一点 也有反应形式

【讨论】:

  • 创建接口实例是不正常的。如果您稍后要绑定到模型的属性,您可以将模型属性置于组件模式:any = {};这样,在设置之前,模型将可以使用空的产品名称属性。
猜你喜欢
  • 2015-08-07
  • 2020-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
  • 2018-12-26
  • 2019-03-10
相关资源
最近更新 更多