【发布时间】: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