Angular 2 dynamic `template variable name`s for DynamicComponentLoader?

后端 未结 2 470
时光说笑
时光说笑 2020-12-16 10:10

TL;DR:

  • works but not dynamic
  • dynamic but doesn\'t work

Explanation:

I\'m dynamically creating

相关标签:
2条回答
  • 2020-12-16 10:57

    After looking around for similar answers, it dawned on me that the default solution is actually very standard: extract a component, where you can hardcode your template variable, and generate as many instances of this component as you need with the *ngFor directive.

    I understand there may be concerns about performance, and I don't know enough about that to comment either way (who knows, it may end up being faster), but IMO it should definitely be the first solution to be envisioned.

    And the DynamicComponentLoader mentionned in Eric Martinez answer seems to be gone from Angular 5 anyway (couldn't find it in the docs).

    0 讨论(0)
  • 2020-12-16 11:09

    The problem with that approach is you can't dynamically generate variable names.

    Another possible approach is using loadAsRoot which instead of using a variable name, uses an id which can contain a dynamic name.

    // This will generate dynamically the id value
    template: `
      <div *ng-for="#idx of data">
        <div id="dynamicid_{{idx}}">Dynamic</div>
      </div>`
    

    Then you set the list you want to iterate over

    this.data = [1,2,3,4,5,6];
    
    for(var i = 0; i < this.data.length; i++) {
      // Third argument is the injector that I'm not using, so I just nulled it
      dynamicComponentLoader.loadAsRoot(DynamicComponent, '#dynamicid_'+this.data[i], null);
    }
    

    Here's the plnkr with an example working.

    I hope it helps.

    0 讨论(0)
提交回复
热议问题