角度8:使用服务创建动态组件。错误:无法读取未定义的属性“ createComponent”

时间:2019-09-19 14:02:14

标签: angular components angular8

我正在尝试使用服务来创建动态组件。当代码在组件中时,我在创建动态组件时没有问题。将代码移至服务时,出现未找到有关createComponent的错误。

我在ngAfterViewInit中调用了函数,这是大多数人在寻找解决方案时遇到的问题。我一直想弄清楚为什么将代码放入服务后我的代码不起作用。我也尝试过做导演,但效果也不佳。

这是堆栈闪电战中的代码 https://stackblitz.com/edit/angular-ikshag

组件和服务代码在下面。

app.component

import { GenService } from './gen.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {
  name = 'Angular';

 constructor(private gen: GenService) { }
  ngAfterViewInit() {
    this.gen.createComp("yo");
  }

}

服务

import { Injectable, ComponentFactoryResolver, ViewChild,ViewContainerRef } from '@angular/core';
import { ChildComponent } from './child/child.component';

@Injectable({
  providedIn: 'root'
})
export class GenService {

  @ViewChild('container', { static: true }) newsHost: ViewContainerRef; //this allow the targeting needed to add component


  constructor(private componentFactoryResolver: ComponentFactoryResolver) { }


  createComp(message) {
    let componentFactory = this.componentFactoryResolver.resolveComponentFactory(ChildComponent);
    let componentRef = this.newsHost.createComponent(componentFactory);//adds it to the screen

  }//end of bot reply

}

子组件只是表示其有效的默认组件。

1 个答案:

答案 0 :(得分:0)

这不是那么简单。您正在阅读的主题(angular-dynamic-components)很长。

看看src/app/dialog/insertion.directive.ts,然后在ng模板中使用其选择器来引用它(而您使用的container选择器没有映射到任何角度指令)。
该指令已插入viewContainerRef,这是用来访问方法createComponent的方式。 ViewChild也非常复杂:@ViewChild(InsertionDirective) insertionPoint: InsertionDirective

所以您要做的步骤是:

  1. 按照博客中的指示进行操作
  2. <ng-template>标签中使用其选择器
  3. 使用指令类更新您的@ViewChild
  4. 访问viewContainerRef您的指令(必须是公共的)以使用createComponent方法