Open
Description
1. 写一个动态组件
动态组件的写法和普通组件没区别
...
@Component({
selector: 'login',
})
export class LoginComponent {}
2. 申明方式
需要在模块的entryComponents
中申明下
@NgModule({
declarations: [LoginComponent],
entryComponents: [LoginComponent]
})
3. 使用方式上很大区别
3.1 方式1
ts
import { LoginComponent } from 'xxx';
...
export class UserComponent{
loginComponent = LoginComponent;
}
html
<ng-container *ngComponentOutlet="loginComponent"></ng-container>
3.2 方式2
html
<ng-template #loginContainer></ng-template>
ts
import { ComponentFactory, ComponentFactoryResolver, OnInit, ViewChild, ViewContainerRef } from '@angular/core';
import { loginComponent } from 'xxx';
export class UserComponent{
loginRef;
@ViewChild('loginContainer', { read: ViewContainerRef, static: true })
loginContainer: ViewContainerRef;
constructor(private cfr: ComponentFactoryResolver){}
ngOnInit() {
this.loginContainer.clear();
const factory: ComponentFactory<any> = this.cfr.resolveComponentFactory(loginComponent);
this.loginRef = this.loginContainer.createComponent(factory);
}
ngOnDestroy(){
// 组件卸载的时候 动态组件也需要卸载
if(this.loginRef){
this.loginRef.destroy()
}
}
}
4. 动态组件传参和事件触发
ngOnInit() {
this.loginContainer.clear();
const factory: ComponentFactory<any> = this.cfr.resolveComponentFactory(loginComponent);
this.loginRef = this.loginContainer.createComponent(factory);
}
@input传参
this.loginRef.instance
是获取组件的实例,someInputProp
是组件中@input
接收的参数。
this.loginRef.instance.someInputProp = value;
Output绑定
this.loginRef.instance
是获取组件的实例,someOutput
是组件中@Output
触发的函数。
this.loginRef.instance.someOutput.subscribe(data => {});
Metadata
Metadata
Assignees
Labels
No labels