繁体   English   中英

在div中动态加载组件 - Angular5

[英]Dynamically load component in div - Angular5

我能够成功创建一个按钮,在单击时将我的组件的另一个实例加载到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”下面呢?

您需要使用自己的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();
  }

}

现在你的home.component.html里面放置了你希望你的编辑器被实例化的地方

<div #container></div>

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM