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

时间:2017-09-11 07:57:06

标签: angular angular5 angular2-hostbinding

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

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

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

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

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

但是我想为所有人做这件事,请帮忙: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() {}
}

和一名工作人员: https://plnkr.co/edit/CVglAPAMIsdQjsqHU4Fb?p=preview

2 个答案:

答案 0 :(得分:8)

您需要传递与添加到<div style="...">sanitize等元素的元素相同的值

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

  constructor(private sanitizer:DomSanitizer) {}

working demo

答案 1 :(得分:0)

如果您想将多个css样式作为字符串或作为具有cammelCase约定的对象来传递,则可以解决以下问题:

父HTML

<app-button [style]="styleFromParent">Some button</app-button>

父组件具有styleFromParent属性,并且如果该属性在某个时刻被更改,则它具有模拟功能:

父组件TS

import { Component, OnInit, ChangeDetectorRef } from '@angular/core';

@Component({
  selector: 'app-site-panel',
  templateUrl: './site-panel.component.html',
})
export class SitePanelComponent implements OnInit {
  constructor(private _detectChanges: ChangeDetectorRef) {}
  styleFromParent = { marginTop: '10px', marginLeft: '50px' };

  ngOnInit() {
    setTimeout(() => {
      this.styleFromParent = { marginTop: '20px', marginLeft: '1px' };

      this._detectChanges.detectChanges();
    }, 2000);
  }
}

子HTML

<ng-content></ng-content>

子组件TS

import { Component, OnInit, HostBinding, Input } from '@angular/core';
import { DomSanitizer, SafeStyle } from '@angular/platform-browser';

@Component({
  selector: 'app-button',
  templateUrl: './button.component.html',
})
export class ButtonComponent implements OnInit {
  @HostBinding('style') baseStyle: SafeStyle;

  @Input()
  set style(style: string | object) {
    let mappedStyles = style as string;

    if (typeof style === 'object') {
      mappedStyles = Object.entries(style).reduce((styleString, [propName, propValue]) => {
        propName = propName.replace(/([A-Z])/g, matches => `-${matches[0].toLowerCase()}`);
        return `${styleString}${propName}:${propValue};`;
      }, '');

      this.baseStyle = this.sanitizer.bypassSecurityTrustStyle(mappedStyles);
    } else if (typeof style === 'string') {
      this.baseStyle = this.sanitizer.bypassSecurityTrustStyle(mappedStyles);
    }
  }

  constructor(private sanitizer: DomSanitizer) {}

  ngOnInit() {}
}

上面,您可以看到baseStyle具有HostBindingstyle组件绑定。 传递style输入时,setter会触发,检查是否传递了字符串或对象,将其解析为字符串并清理该CSS,然后将其分配给baseStyle,这样主机样式就会改变。