Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Style dynamically created Angular component

Tags:

angular

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?

like image 551
SashaSemanyuk Avatar asked Nov 23 '17 15:11

SashaSemanyuk


2 Answers

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

like image 55
Günter Zöchbauer Avatar answered Sep 30 '22 00:09

Günter Zöchbauer


  componentRef.location.nativeElement.style = `
    left: 50px;
    top: 30px;
  `;
like image 31
Martin Cremer Avatar answered Sep 30 '22 01:09

Martin Cremer