在 Angular 中使用 Hostbinding 注入样式声明 [英] Inject Style Declarations Using Hostbinding in Angular

查看:30
本文介绍了在 Angular 中使用 Hostbinding 注入样式声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

@HostBinding('style')获取样式():CSSStyleDeclaration {返回 {背景:'红色',颜色:'石灰'作为 CSSStyleDeclaration;}

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

我可以像这样控制单独的样式声明:

@HostBinding('style.background') 私有背景 = 'red';

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

这是完整的代码:

@Component({选择器:'我的应用',模板:`<div><h2>你好世界!</h2>

`,})出口类应用{//这有效@HostBinding('style.color') 私有颜色 = 'lime';/* 这不起作用@HostBinding('风格')获取样式():CSSStyleDeclaration {返回 {背景:'红色'作为 CSSStyleDeclaration;}*/构造函数(){}}

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

解决方案

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

 @HostBinding('style')get myStyle(): SafeStyle {return this.sanitizer.bypassSecurityTrustStyle('background: red; display: block;');}构造函数(私有消毒剂:DomSanitizer){}

工作演示

Do you guys know how I can batch inject style declarations in a component using the @HostBinding decorator? What I am trying is:

@HostBinding('style')
get style(): CSSStyleDeclaration {
  return {
    background: 'red',
    color: 'lime'
  } as CSSStyleDeclaration;
}

In my understanding this should inject the background and color style to the component, but it does not...

I can control individual style declarations like this:

@HostBinding('style.background') private background = 'red';

but I would like to do it for all of them, please help :P

this is the full code:

@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() {}
}

and a working plunker: https://plnkr.co/edit/CVglAPAMIsdQjsqHU4Fb?p=preview

解决方案

You need to pass the same value you would add to an element like <div style="..."> and sanitize the styles

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

  constructor(private sanitizer:DomSanitizer) {}

working demo

这篇关于在 Angular 中使用 Hostbinding 注入样式声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆