I'm building a component with multiple values, but instead of copying value itself I copy the whole input component:
<ng-content>
<!-- here will be an input component of any type -->
</ng-content>
<button (click)="add()">Add</button>
<div #Container>
</div>
I refence to a @ContentChild
and to a @ViewChild('Container')
- that's not a big deal. However, I couldn't find a smooth way to move input component represented by ContentChild to a container, represented by ViewChild by clicking the Add button.
Here is a workaround what I have now. I reference both of them by ElementRef
and then move down to pure DOM manuipulation:
const elContainer: HTMLElement = this._container.nativeElement;
elContainer.appendChild(this._input.nativeElement);
I wonder if there is a better way.
UPDATE:
@Sreekumar suggested to use CDK Portals, which purpose looks common, but that's have an incredible overhead, look (from an example), and again it uses 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);
}