zoukankan      html  css  js  c++  java
  • [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);
      }
    
    }
  • 相关阅读:
    anaconda安装TensorFlow
    复习NLP-实战(三)
    复习NLP-实战(二)
    复习NLP-实战(一)
    python爬虫实战
    WebSocket实战(一)
    不上传图片直接本地预览
    oracle导出
    使用正则表达式验证学习成绩分数
    限制文本框,文本域输入的字符数量
  • 原文地址:https://www.cnblogs.com/Answer1215/p/6436501.html
Copyright © 2011-2022 走看看