• [Angular] Dynamic components with ComponentFactoryResolver


    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);
      }
    
    }
  • 相关阅读:
    使用 HttpClient 调用第三方接口
    Servlet 的生命周期及工作原理
    SpringBoot 框架简介及搭建
    使用 SimpleDateFormat 获取上个月的日期
    LoadRunner常见问题(一)
    Web_reg_find()函数的使用
    IEtester调试IE6,IE7,IE8,IE9的CSS兼容性的免费工具
    web_find()函数检查中文字符串失败的处理方法
    lr_shoami()的用法
    IP欺骗经验总结
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6436501.html
Copyright © 2020-2023  润新知