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

时间:2019-02-27 06:04:27

标签: css angular angular-directive

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

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

通过属性指令,我可以修改正在使用的父div的CSS。但是希望[mystyles]修改其子元素p和div。

1 个答案:

答案 0 :(得分:1)

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

在父组件中,您可以通过想要的样式(通过@input指令)传递给子组件,然后子组件可以在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的一些指南

编辑:

您可以在父级中编写myClasses变量,以这种方式替换myStyles:

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

然后以这种方式使用子元素中的类:

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

(parentStyle var具有您在@Input()指令后指定的名称,如上例所示)

您可以看到传递多个类只需要一个输入,它仅取决于传递给子代的输入变量。

相关问题