Dynamic template in templatURL in angular2

前端 未结 5 1010
醉话见心
醉话见心 2020-11-30 06:52

I have been using ng-include in angular 1 whenever I had to include a tamplate dynamically in the page.

Now how to acheive this in angular 2. I have tried searching

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-30 07:40

    And as you can see in this issue on the Angular repo, most probably we won't get that directive. There has been a long discussion whether we need this directive or not, and if not provided how we can implement it by our self.

    I tried to make a simple example of how it can be implemented.

    @Component({
        selector: 'my-ng-include',
        template: '
    ' }) export class MyNgInclude implements OnInit { @Input('src') private templateUrl: string; @ViewChild('myNgIncludeContent', { read: ViewContainerRef }) protected contentTarget: ViewContainerRef; constructor(private componentResolver: ComponentResolver) {} ngOnInit() { var dynamicComponent = this.createContentComponent(this.templateUrl); this.componentResolver.resolveComponent(dynamicComponent) .then((factory: any) => this.contentTarget.createComponent(factory)); } createContentComponent(templateUrl) { @Component({ selector: 'my-ng-include-content', templateUrl: templateUrl, directives: FORM_DIRECTIVES, }) class MyNgIncludeContent {} return MyNgIncludeContent ; } }

    For a demo check this Plunker.

提交回复
热议问题