Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

angular - Load ngFor inside insertAdjacentHTML

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...