Is it possible to style the dynamically created component in Angular4? I have the next code:
createComponent(event) {
let componentFactory = this.componentFactoryResolver.resolveComponentFactory(SbImageGalleryPinComponent);
let componentRef = this.pin.createComponent(componentFactory);
document.querySelector('.sb-component-gallery__container').addEventListener('mousemove', this.onMouseMove.bind(this));
}
onMouseMove(event) {
// ????
}
So I want to create component and then set the position left and top relatively to mouse. I am creating component that is sticky to the mouse. Is it possible to reproduce the logic I need?
You can add host binding like shown below in the dynamically added component, and then assign a value to the bound properties after the component was created:
@HostBinding('style.left.px')
left:number;
@HostBinding('style.top.px')
top:number;
componentRef.instance.left = 50;
componentRef.instance.top = 30;
it might be necessary to call
componentRef.changeDetectorRef.detectChanges();
afterwards as well.
See also https://angular.io/api/core/ComponentRef
componentRef.location.nativeElement.style = `
left: 50px;
top: 30px;
`;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With