Skip to content

Angular 动态组件 #61

Open
Open
@deepthan

Description

@deepthan

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

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions