通过属性指令将 CSS 样式传递给子 HTML 元素

Passing CSS Styles to child HTML elements through Attribute Directives

我正在尝试将样式列表发送到要通过属性指令传递的子组件。 例如:

<div [mystyles]>
   <p>.....</p>
   <div>...</div>
</div>

通过属性指令,我可以修改父元素 div 的 css 我 using.But 希望 [mystyles] 修改其子元素 p 和 div.

您可以在 child 组件中使用 ngStyle 指令。

在您的 parent 组件中,您可以(通过 @input 指令)将您想要的样式传递给 child 组件,然后 child 组件可以在您的 html.

这里是示例实现。

Parent.ts

myStyles = {
   'background-color': 'blue',
}

Parent.html

<child-component-selector [parentStyle] = myStyles>

Child.ts

@Input() parentStyle: any;

Child.html

<p [ngStyle]="parentStyle">
   ...
</p>

Here 关于如何使用 ngStyle 的小指南

编辑:

您可以在 parent 中编写替换 myStyles 的 myClasses 变量:

myClasses = {
  "class-name-1": {
    "background-color": "blue"
  },
  "class-name-2": {
    "background-color": "yellow"
  },
  "class-name-3": {
    "background-color": "lime"
  }
}

然后在child元素中使用类这样:

<p [ngStyle]="parentStyle.class-name-1">
   ...
</p>
<div [ngStyle]="parentStyle.class-name-2">
   ...
</div>

(parent样式变量具有您在 @Input() 指令后指定的名称,如上例所示)

如您所见,传递多个 类 只需要一个输入,它仅取决于您传递给 child.

的输入变量