微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – Angular 2将@Component插入另一个组件的DOM中

我有一个组件

import { Component } from '@angular/core';

@Component({
  selector: 'test-component',
  template: '<b>Content</b>',
})
export class TestPage {
  constructor() {}
}
@H_502_7@

我有一个组成部分:

import { Component } from '@angular/core';

@Component({
  selector: 'main-component',
  templateUrl: 'main.html',
})
export class MainPage {

  constructor() {}

  putInMyHtml() {

  }
}
@H_502_7@

main.html中:

<p>stuff</p>
<div> <!-- INSERT HERE --> </div>
@H_502_7@

如何将我的TestPage组件动态插入到<! - INSERT HERE - >的区域中?是以编程方式编写的,就像我运行putInMyHtml一样.

我尝试编辑DOM并插入< test-component>< / test-component>但它不显示TestPage模板中的内容文本.

解决方法:

这是一个带有ComponentFactoryResolver的Plunker Example

首先,您必须正确注册动态组件TestPage

app.module.ts

@NgModule({
  declarations: [MainPage, TestPage],
  entryComponents: [TestPage]
})
@H_502_7@

替代选择

声明dynamic-module.ts

import { NgModule, ANALYZE_FOR_ENTRY_COMPONENTS } from '@angular/core';

@NgModule({})
export class DynamicModule {
  static withComponents(components: any[]) {
    return {
      ngModule: DynamicModule,
      providers: [
        { 
          provide: ANALYZE_FOR_ENTRY_COMPONENTS,
          useValue: components,
          multi: true
        }
      ]
    }
  }
}
@H_502_7@

并在app.module.ts中导入它

@NgModule({
  imports:      [ browserModule, DynamicModule.withComponents([TestPage]) ],
  declarations: [ MainComponent, TestPage ]
})
@H_502_7@

然后您的MainPage组件可能如下所示:

import { ViewChild, ViewContainerRef, ComponentFactoryResolver } from '@angular/core';
@Component({
  selector: 'main-component',
  template: `
    <button (click)="putInMyHtml()">Insert component</button>
    <p>stuff</p>
    <div>
       <template #target></template> 
    </div>
  `
})
export class MainPage {
  @ViewChild('target', { read: ViewContainerRef }) target: ViewContainerRef;
  constructor(private cfr: ComponentFactoryResolver) {}

  putInMyHtml() {
    this.target.clear();
    let compFactory = this.cfr.resolveComponentFactory(TestPage);

    this.target.createComponent(compFactory);
  }
}
@H_502_7@
                
                                 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐