【问题标题】:Dynamically load component in div - Angular5在 div 中动态加载组件 - Angular5
【发布时间】:2018-07-21 09:27:08
【问题描述】:

我能够成功创建一个按钮,单击该按钮将我的组件的另一个实例加载到 DOM 中,但它将它加载到我希望它位于其中的组件之外,结果导致 CSS 关闭。当我将“editorComponents”添加到我的页面时,它当前看起来像这样:

但我希望它看起来像这样:

您可以从检查中看到,在第二个示例中,所有标签都被手动移动到我想要的位置。

现在我的代码如下:

home.component.html

<div class="row backgroundContainer">

  <div class="col-md-7 componentContainer">
    <app-editor></app-editor>
    <button (click)="addEditor()" type="button">Add Editor</button>
  </div>

  <div class="col-md-5 componentContainer">
    <app-bible></app-bible>
  </div>

  <div id="footerBox">
    <app-footer></app-footer>
  </div>
  
</div>

home.component.ts

import { Component, OnInit, ViewContainerRef, ComponentFactoryResolver } from '@angular/core';
import { EditorComponent } from '../editor/editor.component';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {

  constructor(private componentFactoryResolver: ComponentFactoryResolver,
    private viewContainerRef: ViewContainerRef) {}

  ngOnInit() {
  }

  addEditor() {
    const factory = this.componentFactoryResolver.resolveComponentFactory(EditorComponent);
    const ref = this.viewContainerRef.createComponent(factory);
    ref.changeDetectorRef.detectChanges();
  }

}

那么,当我将 EditorComponent 动态添加到我的页面时,我该如何做到这一点,它会直接添加到我的 html 中当前“app-editor”的下方?

【问题讨论】:

    标签: angular view components


    【解决方案1】:

    您需要使用自己的ViewContainerRef。目前您正在注入 root 1,您可以看到所有组件都附加到 &lt;app-root&gt;

    import { Component, OnInit, ViewContainerRef, ComponentFactoryResolver } from '@angular/core';
    import { EditorComponent } from '../editor/editor.component';
    
    @Component({
      selector: 'app-home',
      templateUrl: './home.component.html',
      styleUrls: ['./home.component.scss']
    })
    export class HomeComponent implements OnInit {
      // Setup custom viewChild here
      @ViewChild('container', { read: ViewContainerRef }) viewContainerRef: ViewContainerRef;    
    
      constructor(private componentFactoryResolver: ComponentFactoryResolver) {}
    
      ngOnInit() {
      }
    
      addEditor() {
        const factory = this.componentFactoryResolver.resolveComponentFactory(EditorComponent);
        const ref = this.viewContainerRef.createComponent(factory);
        ref.changeDetectorRef.detectChanges();
      }
    
    }
    

    现在在您的 home.component.html 中,将其放在您希望编辑器实例化的位置

    <div #container></div>
    

    您可以在此处使用任何 html 标签。

    现在您的所有编辑器都将在此块内。

    【讨论】:

    • 如果不想引入div,请使用&lt;ng-template #container&gt;&lt;/ng-template&gt;
    • 添加 ViewChild 以从 angular/core 导入
    • 你不需要 detectChanges() 调用吗?
    猜你喜欢
    • 1970-01-01
    • 2018-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多