Angular 2+从标记创建ViewRef注入动态模板 [英] Angular 2+ Create ViewRef from Markup Injected into Dynamic Template

查看:324
本文介绍了Angular 2+从标记创建ViewRef注入动态模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从动态插入到模板中的标记创建一个ViewRef。这是否可能基于以下代码示例?

I would like to create a ViewRef from markup that is dynamically inserted into a template. Is this possible based on the following code sample?

template.html

<ng-container *ngTemplateOutlet="dynamic; context: cntx"></ng-container>
<ng-template #dynamic>
  <div [innerHTML]="markup"></div>
</ng-template>

从API调用中注入绑定到div的innerHTML属性的标记:

Injected markup from API call to bind to div's innerHTML attribute:

<div>
    <div id="forViewRef"></div>
</div>

component.ts

@ContentChild('#forViewRef', { read: ViewContainerRef }): someHndl;
private _nativeElem: any;

constructor(
    private sanitizer: DomSanitizer, 
    private _vcRef: ViewContainerRef, 
    private _resolver: ComponentFactoryResolver) {
    // to ensure template has been created, #dynamic
    this._nativeElem = this._vcRef.element.nativeElement;
}

// listen to lifecycle hook
ngAfterContentChecked() {
    if (this._nativeElem !== undefined)
        // childContent ref is undefined
        console.log(this.someHndl);
        // markup is in the DOM
        console.log(this._nativeElem.querySelectorAll('#forViewRef'));
}


推荐答案

code>< div id =forViewRef>< / div> 您可以执行以下操作:

To create component dynamically inside <div id="forViewRef"></div> you can do the following:

我们需要加载以下组件

@Component({
  selector: 'dynamic-comp',
  template: `
   <h2>Dynamic component</h2>
    <button (click)="counter = counter + 1">+</button> {{ counter }}
  `
})
export class DynamicComponent {
  counter = 1;
}

所以首先将它添加到声明 entryComponents 您的 @NgModule的数组

so first add it to declarations and entryComponents array of your @NgModule

  ...
  declarations: [ ..., DynamicComponent ],
  entryComponents: [ DynamicComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

之后创建

template.html

<button (click)="createComponent()">Create component</button>

<div id="forViewRef"></div>

最后写入

component.ts

export class AppComponent {
  compRef: ComponentRef<DynamicComponent>;

  constructor(private injector: Injector,
              private resolver: ComponentFactoryResolver,
              private appRef: ApplicationRef) {}


  createComponent() {
    const compFactory = this.resolver.resolveComponentFactory(DynamicComponent);
    this.compRef = compFactory.create(this.injector, null, '#forViewRef');

    this.appRef.attachView(this.compRef.hostView);
  }

  ngOnDestroy() {
    if(this.compRef) {
      this.compRef.destroy();
    }
  }
}

我使用 appRef.attachView 为了包含动态组件来更改检测周期

I use appRef.attachView in order to include dynamic component to change detection cycle

Plunker示例

Plunker Example

另请参见

Angular2 - 组件转换为动态创建元素

使用指令向组件动态添加组件

这篇关于Angular 2+从标记创建ViewRef注入动态模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆