在Angular中使用Hostbinding注入样式声明

And*_*icu 5 angular2-hostbinding angular angular5

你们知道如何使用@HostBinding装饰器在组件中批量注入样式声明吗?我在想的是:

@HostBinding('style')
get style(): CSSStyleDeclaration {
  return {
    background: 'red',
    color: 'lime'
  } as CSSStyleDeclaration;
}
Run Code Online (Sandbox Code Playgroud)

在我的理解中,这应该为组件注入背景和颜色样式,但它不...

我可以像这样控制各个样式声明:

@HostBinding('style.background') private background = 'red';
Run Code Online (Sandbox Code Playgroud)

但我想为所有人做这件事,请帮助:P

这是完整的代码:

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello world!</h2>
    </div>
  `,
})
export class App {

  // This works
  @HostBinding('style.color') private color = 'lime';

  /* This does not work
  @HostBinding('style')
  get style(): CSSStyleDeclaration {
    return {
      background: 'red'
    } as CSSStyleDeclaration;
  }
  */

  constructor() {}
}
Run Code Online (Sandbox Code Playgroud)

和一个工作的plunker:https://plnkr.co/edit/CVglAPAMIsdQjsqHU4Fb p = preview

Gün*_*uer 9

您需要传递与添加到元素相同的值,<div style="...">清理样式

  @HostBinding('style')
  get myStyle(): SafeStyle {
    return this.sanitizer.bypassSecurityTrustStyle('background: red; display: block;');
  }

  constructor(private sanitizer:DomSanitizer) {}
Run Code Online (Sandbox Code Playgroud)

工作演示