【发布时间】:2018-09-25 20:39:26
【问题描述】:
我有一个关于使用resolveComponentFactory 创建新组件的问题。首先有一个startComponent(父组件),从这个组件有几个按钮,每个 btn 创建一个新的子组件。例如,现在我创建了一个“childComponent”,这也有效。但是现在我想在childComponent 中创建一个新的childComponent,并且这个新组件应该有startComponent 作为父组件,而不是childComponent 本身。所以我需要一种方法来使用我的childComponent 从startComponent 调用addComponent() 方法。
这是我目前的做法:
startComponent.ts:
import {
Component, OnInit, ViewChild,
ComponentFactoryResolver,
ViewContainerRef
} from '@angular/core';
Import { childComponent } from '../childComponent/child.component';
import { DataService } from '../data.service';
@Component({
selector: 'app-start',
templateUrl: './start.component.html',
styleUrls: ['./start.component.css']
})
export class startComponent implements OnInit {
@ViewChild('parent', { read: ViewContainerRef }) container: ViewContainerRef;
constructor(private dataService: DataService, private componentFactoryResolver: ComponentFactoryResolver){}
ngOnInit(){}
addComponent(){
let componentFactory = this.componentFactoryResolver.resolveComponentFactory(childComponent);
let component = this.container.createComponent(componentFactory);
// next Line i save the reference of the "childComponent" to a Service
// so the "childComponent" can get it and destroy himself if wanted
this.createComponentService.setReference(component, type);
}
}
startComponent.html
<div>
<span matTooltip="Select"><button (click)="addComponent()" class="btn">
<img class="img" src="./assets/StartIcons/childCreate-icon.png" alt="not found"> </button></span>
</div>
<div #parent></div>
如果我想用我的childComponent 创建一个childComponent,它确实有效,但startComponent 不是父组件。
希望您能理解我的问题,否则我可以尝试再次解释。
【问题讨论】:
-
请过去完整的 startComponent.ts 和 .html 代码。
-
好的,我编辑了文本
标签: html angular typescript components parent-child