9

你们知道如何使用@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() {}
}

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

4

2 回答 2

15

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

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

  constructor(private sanitizer:DomSanitizer) {}

工作演示

于 2017-09-11T08:53:39.927 回答
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因此主机样式将发生变化。

于 2019-07-29T13:08:21.987 回答