Load ngFor inside insertAdjacentHTML

2019-09-20 12:21发布

问题:

I am attaching element inside template dynamically by user click, this way:

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);
}

However the {{lup.name}} doesn't print the actual value but as how it is typed there. How to make it works? Anybody?

UPDATE:

I've tried with this way, but still it's said that

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

回答1:

Angular doesn't process Angular specific markup like matching component or directive selectors or bindings for dynamically added HTML.

Angular generates code for these things when it compiles components. What is not in a components template when the component is compiled, is completely ignored by Angular.

What you can do is to dynamically create and compile Angular components at runtime. For more details see How can I use/create dynamic template to compile dynamic Component with Angular 2.0?