angularcss-gridangular2-hostbinding

Why can I not use @HostBinding on shorthand CSS grid properties?


When using @HostBinding on shorthand CSS grid properties (e.g. using grid-row instead of grid-row-start and grid-row-end) the bindings don't work:

export class MyComponent {
  @HostBinding('style.grid-row')
  row = '1 / 2';
}

However using the individual properties does work:

export class MyComponent {
  @HostBinding('style.grid-row-start')
  row = 1;

  @HostBinding('style.grid-row-end')
  row = 2;
}

Is this intentional or a bug with Angular? Of course a work around is to just not use the shorthand properties.

Stackblitz: https://stackblitz.com/edit/angular-qfotyg


Solution

  • Since you are adding style directly to DOM, Angular consider the value as unstrusted. Use DomSanitizer to turn the unstrusted values into trusted value

    DomSanitizer

    Sanitization is the inspection of an untrusted value, turning it into a value that's safe to insert into the DOM. In many cases, sanitization doesn't change a value at all. Sanitization depends on context: a value that's harmless in CSS is potentially dangerous in a URL.

    export class AppGridCellBrokenComponent {
      @Input()
      text: string;
    
      @HostBinding('style.grid-row')
      get gridRow() {
        return this.sanitizer.bypassSecurityTrustStyle(`${this.rowStart} / ${this.rowEnd}`);
      }
    
      @HostBinding('style.grid-column')
      get gridColumn() {
        return this.sanitizer.bypassSecurityTrustStyle(`${this.columnStart} / ${this.columnEnd}`)
      }
    
      constructor(private sanitizer:DomSanitizer){
    
      }
    }
    

    ForkedExample

    Ref