创建组件并追加到div

时间:2019-04-01 02:39:46

标签: angular angularjs-directive

我有一个带有指令<div>的{​​{1}},因此我可以创建一个组件并将其附加到该组件。

[appComponent]

我的指令如下:

<div [appComponent]="component">

还有我的@Directive({ selector: '[appComponent]' }) export class ComponentDirective implements OnChanges { @Input('appComponent') comp: any; private container; constructor(private elementRef: ElementRef, private renderer: Renderer2) { this.container = this.elementRef.nativeElement; } ngOnChanges(changes: SimpleChanges): void { const newComponent = this.renderer.createElement('new-component'); this.renderer.appendChild(this.container, newComponent); } }

new-component

此组件内部包含内容。 该元素已创建并附加到div,但是它为空:

@Component({
  selector: 'new-component',
  templateUrl: './new-component.html',
  styleUrls: ['./new-component.scss']
})
export class NewComponent {
}

如何实例化组件并将其附加到div?我正在使用角度7。

2 个答案:

答案 0 :(得分:0)

尝试使用ViewContainerRefComponentFactoryResolver

let componentFactory = 
    this.componentFactoryResolver.resolveComponentFactory(NewComponent);
let componentInstance = 
    this.viewContainerRef.createComponent(componentFactory);
this.renderer.appendChild(this.container, 
    componentInstance.location.nativeElement);

答案 1 :(得分:0)

您不需要ElementRefRenderer2

尝试以下方法:

@Directive({
  selector: '[appComponent]'
})
export class ComponentDirective implements OnChanges {
  @Input('appComponent') comp: any;

  constructor(private componentFactoryResolver: ComponentFactoryResolver, public viewContainerRef: ViewContainerRef) {
  }

  ngOnChanges(changes: SimpleChanges): void {
    const componentFactory = this.componentFactoryResolver.resolveComponentFactory(NewComponent);
    const componentRef = this.viewContainerRef.createComponent(componentFactory);
    this.viewContainerRef.insert(componentRef.hostView);
  }
}

要提及的一件事是,要完成这项工作,您必须将NewComponent添加到entryComponents,如下所示:

@NgModule({
  imports [...],
  entryComponents: [NewComponent],
  declarations: [NewComponent, ComponentDirective, ...],
  bootstrap: [...]
})
export class AppModule { }

这是一个有效的示例:https://stackblitz.com/edit/angular-dbszef