[Angular] Dynamic components with ComponentFactoryResolver

本文介绍如何在Angular中通过ViewContainerRef和ComponentFactoryResolver动态创建组件。首先,在模板中添加带有ref的容器;然后,使用@ViewChild获取ViewContainerRef;接着,注入ComponentFactoryResolver;最后,在ngAfterContentInit中创建组件。

To create a component dynamicly.

 

1. Add a container with ref:

@Component({
  selector: 'app-root',
  template: `
    <div>
      <div #entry>
        <!-- We want to create auth-form component inside this div-->
      </div>
    </div>
  `
})

 

2. View this container as ViewContainerRef.

@ViewChild('entry', {read: ViewContainerRef}) entry: ViewContainerRef;

 

3. We need ComponentFactoryResolver:

  constructor(private resolver: ComponentFactoryResolver) {

  }

 

4. We will create compoennt after content init:

export class AppComponent implements AfterContentInit{
  ngAfterContentInit() {

  }
}

 

5. Create factory by using resolver:

  ngAfterContentInit() {
    const factory = this.resolver.resolveComponentFactory(AuthFormComponent);
   
  }

 

6. Create component by using viewContainerRef:

  ngAfterContentInit() {
    const factory = this.resolver.resolveComponentFactory(AuthFormComponent);
    this.entry.createComponent(factory);
  }

 

7. Make sure, you add entryComponent:

@NgModule({
  declarations: [
    AuthFormComponent,
    AuthRememberComponent,
    AuthMessageComponent
  ],
  imports: [
    CommonModule,
    FormsModule
  ],
  exports: [
    AuthFormComponent,
    AuthRememberComponent
  ],
  entryComponents: [
    AuthFormComponent
  ]
})

 

// app.component:

import {Component, ViewContainerRef, ViewChild, ComponentFactoryResolver, AfterContentInit} from '@angular/core';

import { AuthFormComponent } from './auth-form/auth-form.component';

import { User } from './auth-form/auth-form.interface';

@Component({
  selector: 'app-root',
  template: `
    <div>
      <div #entry>
        <!-- We want to create auth-form component inside this div-->
      </div>
    </div>
  `
})
export class AppComponent implements AfterContentInit{

  @ViewChild('entry', {read: ViewContainerRef}) entry: ViewContainerRef;

  constructor(private resolver: ComponentFactoryResolver) {

  }

  ngAfterContentInit() {
    const factory = this.resolver.resolveComponentFactory(AuthFormComponent);
    this.entry.createComponent(factory);
  }

  loginUser(user: User) {
    console.log('Login', user);
  }

}

 

转载于:https://www.cnblogs.com/Answer1215/p/6436501.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值