【问题标题】:How to use createEmbeddedView method of TemplateRef in angular4?如何在angular4中使用TemplateRef的createEmbeddedView方法?
【发布时间】:2017-12-22 09:44:40
【问题描述】:

我开始学习 Angular 中的 DOM 操作,并注意到 templateRef 及其方法 createEmbeddedView。我更想了解这种方法。现在我的问题是,如何使用这个方法的createEmbeddedView

@Component({
  selector: 'app-root',
  template: `
<ng-template #template>

</ng-template>
  `
})
export class AppComponent implements AfterViewChecked {
        @ViewChild('template', { read: TemplateRef }) _template: TemplateRef<any>;      
  constructor() { }

  ngAfterViewChecked() {
    this._template.createEmbeddedView('this is a embedded view')
  }
}

【问题讨论】:

    标签: angular angular-template


    【解决方案1】:

    您可以使用createEmbeddedView 方法创建一个嵌入式视图,然后通过ViewContainerRef 将该视图附加到DOM:

    @Component({
        selector: 'app-root',
        template: `
            <ng-template #template let-name='fromContext'><div>{{name}}</ng-template>
            <ng-container #vc></ng-container>
        `
    })
    export class AppComponent implements AfterViewChecked {
        @ViewChild('template', { read: TemplateRef }) _template: TemplateRef<any>;
        @ViewChild('vc', {read: ViewContainerRef}) vc: ViewContainerRef;
        constructor() { }
    
        ngAfterViewChecked() {
            const view = this._template.createEmbeddedView({fromContext: 'John'});
            this.vc.insert(view);
        }
    }
    

    或者您可以直接使用ViewContainerRef 创建视图:

    ngAfterViewChecked() {
        this.vc.createEmbeddedView(this._template, {fromContext: 'John'});
    }
    

    上下文是一个具有属性的对象,您可以通过let- 绑定访问这些属性。

    要了解更多信息,请阅读 Exploring Angular DOM manipulation techniques using ViewContainerRef 并参阅 this answer

    【讨论】:

    • 上下文类型是什么,是字符串吗?还有vc代表什么,是viewContainerRef吗?
    • 是的,我明白这一点,但我的问题是您在代码中也提到的“上下文”类型是什么。是否是一个取值的字符串 ie.
      这是一个动态元素
    • @LijinJohn,我刚刚添加了一个在模板中使用上下文对象属性的示例
    • @LijinDurairaj,我的回答还有什么不清楚的地方吗?
    • @LijinDurairaj 如果回答了您的问题,请将此标记为答案。
    猜你喜欢
    • 2019-04-21
    • 2018-01-14
    • 2018-05-13
    • 2018-10-29
    • 2019-01-27
    • 1970-01-01
    • 1970-01-01
    • 2017-12-15
    • 2018-09-17
    相关资源
    最近更新 更多