【发布时间】:2018-02-11 11:37:59
【问题描述】:
我正在构建一个具有多个值的组件,但不是复制值本身,而是复制整个输入组件:
<ng-content>
<!-- here will be an input component of any type -->
</ng-content>
<button (click)="add()">Add</button>
<div #Container>
</div>
我参考@ContentChild 和@ViewChild('Container') - 这没什么大不了的。但是,我找不到通过单击“添加”按钮将由 ContentChild 表示的输入组件移动到由 ViewChild 表示的容器的平滑方法。
这是我现在拥有的解决方法。我通过ElementRef 引用它们,然后向下移动到纯DOM 操作:
const elContainer: HTMLElement = this._container.nativeElement;
elContainer.appendChild(this._input.nativeElement);
不知道有没有更好的办法。
更新:
@Sreekumar 建议使用 CDK 门户,其目的看起来很常见,但它的开销令人难以置信,看看(来自示例),它再次使用 DOM:
constructor(
private componentFactoryResolver: ComponentFactoryResolver,
private injector: Injector,
private appRef: ApplicationRef,
) { }
ngOnInit() {
// Create a portalHost from a DOM element
this.portalHost = new DomPortalHost(
document.querySelector('#pageHeader'),
this.componentFactoryResolver,
this.appRef,
this.injector
);
// Locate the component factory for the HeaderComponent
this.portal = new ComponentPortal(HeaderComponent);
// Attach portal to host
this.portalHost.attach(this.portal);
}
【问题讨论】:
-
试试 CDK Porals : material.angular.io/cdk/portal/overview
-
@Sreekumar,这看起来像是 Material 的一部分,有什么与主题无关的方式吗?
-
@Vladimir 这不是 Material 的一部分。这是一个由 Material 团队维护的通用库。
-
是的,在深入学习之后感谢您,这确实是一个好方法。然而,这只与我对一个相当大的 UI 库的需求有关,如果我要运行一个小项目,我认为添加这个库会太多,所以我希望 @angular/core 有办法做到这一点。跨度>
标签: angular