【问题标题】:Load ngFor inside insertAdjacentHTML在 insertAdjacentHTML 中加载 ngFor
【发布时间】:2018-05-19 05:00:50
【问题描述】:

我通过用户点击在模板内动态附加元素,这样:

this.optionValue = [];

youClickMe(){
  var moreput = '';
      moreput += '<select">';
        moreput += '<option *ngFor="let lup of optionValue">{{lup.name}}</option>';
      moreput += '</select>';
  var pElement = document.querySelector('.somewhereyoubelong');
      pElement.insertAdjacentHTML('beforeend', moreput);
}

但是 {{lup.name}} 不会打印实际值,而是在其中键入它的方式。如何使它起作用?有人吗?

更新:

这种方式我试过了,但还是有人说

const templating = '<p *ngFor="let sizeCat of sizeCategoryBySubCategory" [value]="sizeCat.id">{{sizeCat.name}}</p>';

const tmpCmp = Component({template: templating})(class {});
const tmpModule = NgModule({declarations: [tmpCmp]})(class {});

this._compiler.compileModuleAndAllComponentsAsync(tmpModule).then((factories) => {
  const f = factories.componentFactories[0];
  const cmpRef = f.create(this._injector, [], null, this._m);

  //cmpRef.instance.testText = 'B component';
  cmpRef.instance.sizeCategoryBySubCategory = [
    { id:1, name: 'a'},
    { id:2, name: 'b'},
  ];

  this._container.insert(cmpRef.hostView);
});

Property binding ngForOf not used by any directive on an embedded template

【问题讨论】:

  • 请不要这样做。我想知道你写这样的代码为什么需要这个框架
  • @yurzui,我正在这样做。应该如何,如何解决问题?非常感谢。
  • 这部分是独一无二的,所以其实和framework关系不大。该框架的真正目的是为了散列。

标签: angular typescript


【解决方案1】:

Angular 不会处理 Angular 特定的标记,例如匹配组件或指令选择器或动态添加 HTML 的绑定。

Angular 在编译组件时会为这些东西生成代码。 编译组件时组件模板中没有的内容会被 Angular 完全忽略。

您可以做的是在运行时动态创建和编译 Angular 组件。更多详情见How can I use/create dynamic template to compile dynamic Component with Angular 2.0?

【讨论】:

  • 非常感谢您来这里回复。我有点困惑如何做这种有角度的方式,就像你在我评论的上一个答案中所说的'DynamicComponentLoader',我在想它是否与此有关。
  • 您首先需要按照上面链接的答案中所述动态创建一个组件,然后您可以使用ViewContainerRef.createComponent(以前为DynamicComponentLoader)将该组件添加到另一个组件
  • 好吧,我还需要在那里导入browser 模块才能使其正常工作。
  • 现在,我只是想知道为什么 Angular 让简单的事情变得如此复杂,虽然我们不能说我们需要使用另一个框架来处理这样的事情,但它不是程序员的编程立场。
  • 等等,数据没有插入到父母内部。
猜你喜欢
  • 1970-01-01
  • 2018-01-18
  • 2019-04-19
  • 2019-05-11
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 2020-05-25
  • 2020-08-13
相关资源
最近更新 更多