在div中动态加载组件 - Angular5

Fra*_*ank 6 components view angular

我能够成功创建一个按钮,在单击时将我的组件的另一个实例加载到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>
Run Code Online (Sandbox Code Playgroud)

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();
  }

}
Run Code Online (Sandbox Code Playgroud)

那么当我动态地将EditorComponent添加到我的页面时,如何将它直接添加到我的html中的当前"app-editor"下面呢?

Vit*_*vzh 12

你需要使用自己的ViewContainerRef.目前您正在注入root one,因为您可以看到附加到的所有组件<app-root>.

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();
  }

}
Run Code Online (Sandbox Code Playgroud)

现在在你的内部home.component.html你想要你的编辑器实例化

<div #container></div>
Run Code Online (Sandbox Code Playgroud)

你可以在这里使用任何html标签.

现在你所有的编辑都将在这个街区内.

  • 如果您不想引入*div*,请使用`<ng-template #container> </ ng-template>`. (3认同)
  • 添加 ViewChild 以从 angular/core 导入 (3认同)