如何在其他组件中插入组件
How to plugin a Component in a Component other
我有一个组件是 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;
}
点击按钮时如何在A组件中插入B组件?
感谢阅读我的问题。
您可以这样使用 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');
}
}
这个例子来自 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');
}
我有一个组件是 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;
}
点击按钮时如何在A组件中插入B组件?
感谢阅读我的问题。
您可以这样使用 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');
}
}
这个例子来自 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');
}