【问题标题】:document setAttribute ngModel Angular文档 setAttribute ngModel Angular
【发布时间】:2017-10-17 18:02:25
【问题描述】:

我正在尝试以角度 4 创建从 typescript 到 html 的输入元素。但是当我尝试 put [(ngModel)] 时不起作用。我怎么做那个方法?有人知道吗?

createElement() {
    this.input = document.createElement('input');
    this.input.setAttribute('matInput', '');
    this.input.setAttribute('placeholder', 'Tema');
    this.input.setAttribute('[(ngModel)]', 'module.theme');
    this.input.setAttribute('name', 'theme');

    return (<HTMLDivElement>(document.getElementById('ejemplo').appendChild(this.input)));
  }

【问题讨论】:

    标签: html angular typescript


    【解决方案1】:

    类似

     this.input.setAttribute('[(ngModel)]', 'module.theme');
    

    不应该工作。 属性/属性绑定和组件/指令实例化仅发生在静态添加到组件模板的标记中。

    如果它是动态添加的,它不会有任何效果。 如果需要,您可以在运行时创建和编译组件,然后动态添加该组件(添加到静态定义的ViewContainerRef)。

    您也可以使用命令式代码来更新 DOM。

    【讨论】:

    • 那么“创建和编译组件”这件事怎么办?
    • 这个答案stackoverflow.com/a/46578036/217408中的链接似乎是最近的。 SO还有其他几个相关的问题/答案。
    • 谢谢,但这会从 html 字符串而不是 HTMLElement 对象创建组件。不调用 .innerHTML 有可能吗?以及如何在指令中做到这一点(只能访问 ElementRef 而不能访问 ViewContainerRef)?
    • 抱歉,这个话题我帮不了你。我自己从来没有用过。
    猜你喜欢
    • 2018-12-14
    • 2018-02-17
    • 1970-01-01
    • 1970-01-01
    • 2016-11-19
    • 2017-06-27
    • 2020-09-12
    • 1970-01-01
    • 2014-02-14
    相关资源
    最近更新 更多