bubbles
bubbles

Reputation: 2727

WARNING: sanitizing unsafe style value

With version 7 of Angular i have this simple code :

@Component({
  selector: 'nf-delete',
  template: `
    <span [title]="title" class="mdi mdi-close-circle font-size-medium">
    </span>
  `,
  styles: [
      `
      :host {
        cursor: pointer;
        line-height: 1;
        vertical-align: middle;
      }

      :host(.inline) {
        display: inline-block;
      }
    `
  ]
})
export class DeleteComponent {
  @Input() title = 'Delete';
  @Input() inline = false;

  @HostBinding('class.inline')
  get isInline() {
    return this.inline;
  }
}

I wrote another version:

@Component({
  selector: 'nf-delete',
  template: `
    <span [title]="title" class="mdi mdi-close-circle font-size-medium">
    </span>
  `,
  styles: [
      `
      :host {
        cursor: pointer;
        line-height: 1;
        vertical-align: middle;
      }
    `
  ]
})
export class DeleteComponent {
  @Input() title = 'Delete';

  constructor(private readonly sanitizer: DomSanitizer, private el: ElementRef, private rendrer: Renderer2) {
  }

  @Input() set inline(inline: boolean) {
    inline && this.rendrer.setStyle(this.el.nativeElement, 'display', this.sanitizer.bypassSecurityTrustStyle('inline-block'));
  }
}

The two versions output the warning below:

core.js:13290 WARNING: sanitizing unsafe style value [object Object] (see http://g.co/ng/security#xss).

Anyone knows how to fix this warning ?

Upvotes: 1

Views: 2438

Answers (1)

Danylo Gudz
Danylo Gudz

Reputation: 2656

Use HostBinding to set attributes/styles on host element during change detection.

Here I've implemented small demo for your case: https://stackblitz.com/edit/angular-k9sr9d

inline: boolean;
@HostBinding('style.display') get disp() {
  return this.inline ? 'inline-block' : '';
}

Upvotes: 2

Related Questions