We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
动态组件的写法和普通组件没区别
... @Component({ selector: 'login', }) export class LoginComponent {}
需要在模块的entryComponents中申明下
entryComponents
@NgModule({ declarations: [LoginComponent], entryComponents: [LoginComponent] })
ts
import { LoginComponent } from 'xxx'; ... export class UserComponent{ loginComponent = LoginComponent; }
html
<ng-container *ngComponentOutlet="loginComponent"></ng-container>
<ng-template #loginContainer></ng-template>
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() } } }
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
@input
this.loginRef.instance.someInputProp = value;
Output绑定 this.loginRef.instance是获取组件的实例,someOutput是组件中@Output 触发的函数。
someOutput
@Output
this.loginRef.instance.someOutput.subscribe(data => {});
The text was updated successfully, but these errors were encountered:
No branches or pull requests
1. 写一个动态组件
动态组件的写法和普通组件没区别
2. 申明方式
需要在模块的
entryComponents
中申明下3. 使用方式上很大区别
3.1 方式1
ts
html
3.2 方式2
html
ts
4. 动态组件传参和事件触发
@input传参
this.loginRef.instance
是获取组件的实例,someInputProp
是组件中@input
接收的参数。Output绑定
this.loginRef.instance
是获取组件的实例,someOutput
是组件中@Output
触发的函数。The text was updated successfully, but these errors were encountered: