簡體   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