警告:清理不安全的样式值

时间:2018-12-26 15:39:57

标签: angular typescript

在Angular 7版本中,我有以下简单代码:

@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;
  }
}

我写了另一个版本:

@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'));
  }
}

两个版本在下面输出警告:

  

core.js:13290警告:清理不安全的样式值[object Object]   (请参阅http://g.co/ng/security#xss)。

有人知道如何解决此警告吗?

1 个答案:

答案 0 :(得分:0)

在更改检测期间,使用HostBinding在宿主元素上设置属性/样式。

在这里,我已经为您的案例实施了一个小型演示:https://stackblitz.com/edit/angular-k9sr9d

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