angularangular-componentsng-style

Apply CSS style to angular componet from within the component


If I create a very simple component in angular with the following html:

<div [ngStyle]="{ 'grid-column-start':  colStart }" >
  testing
</div>

The component typescript file contains 1 input

  @Input() colStart: number;

I want to use the component within a css grid however when the component in rendered in the dom it's wrapped in a element for the component

<app-test-component _ngcontent-fsq-c305="" _nghost-fsq-c298="" ng-reflect-col-start="3">
    <div _ngcontent-fsq-c298="" ng-reflect-ng-style="[object Object]" style="grid-column-start: 3;">
        testing
    </div>
</app-test-component>

So in the example above I'm trying to position the component within a grid but it doesn't work as the css property in on the div and not the component.

How can I resolve this?

I've created this StackBlitz to demo the issue:

Example

Thanks


Solution

  • your grid-item-component can be like

    <div class="grid-item">
      <ng-content></ng-content>
    </div>
    
    
    export class GridItemComponent implements OnInit {
      @Input() set colStart(value:number)
      {
        this.el.nativeElement.style['grid-column-start']=value
      }
    
      constructor(private el:ElementRef) {}
    
      ngOnInit() {
      }
    }