Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Angular 动态组件 #61

Open
deepthan opened this issue Jun 17, 2020 · 0 comments
Open

Angular 动态组件 #61

deepthan opened this issue Jun 17, 2020 · 0 comments

Comments

@deepthan
Copy link
Owner

deepthan commented Jun 17, 2020

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 => {});
@deepthan deepthan changed the title Angular 动态组件写法 Angular 动态组件 Jun 17, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant