我有一个组件是A,它是index.html的插件,它的模板是:
<div> content of A </div>
<component-will-plugin></component-will-plugin>
<button (click)="pluginBtoA()">click me to plugin B to plugin A </button>
和函数pluginBtoA的代码:
pluginBtoA(){
redirectToB;
}
单击按钮时,如何在组件中插入B组件?
感谢您阅读我的问题。
答案 0 :(得分:2)
您可以这样使用DynamicComponentLoader
及其loadIntoLocation
方法:
@Component({
selector: 'my-app',
template: `
Parent
<div #child></div>
<div (click)="onClick()">Add sub component</div>
`
})
export class MyApp {
constructor(private dcl: DynamicComponentLoader,
private elementRef: ElementRef) {
}
onClick() {
this.dcl.loadIntoLocation(ChildComponent, this.elementRef, 'child');
}
}
答案 1 :(得分:2)
此示例来自Angular2 IO页面。
@Component({
selector: 'child-component',
template: 'Child'
})
class ChildComponent {
}
@Component({
selector: 'my-app',
template: 'Parent (<div #child></div>)'
})
class MyApp implements OnInit {
constructor(private dcl: DynamicComponentLoader, private elementRef: ElementRef) {
}
ngOnInit(){
this.dcl.loadIntoLocation(ChildComponent, this.elementRef, 'child');
}
}
您可以阅读有关此https://angular.io/docs/ts/latest/api/core/DynamicComponentLoader-class.html#!#loadIntoLocation
的信息现在,您可以在单击
时在调用函数中移动此this.dcl.loadIntoLocation(ChildComponent, this.elementRef, 'child');
例如:
pluginBtoA(){
//redirectToB;
this.dcl.loadIntoLocation(ChildComponent, this.elementRef, 'child');
}