通过Attribute Directives将CSS样式传递给子HTML元素

问题描述 投票:1回答:1

我试图通过属性指令传递子组件的样式列表。例如:

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

通过属性指令,我可以修改我正在使用的父div的css。但是想要[mystyles]修改它的子元素p和div。

css angular angular-directive
1个回答
2
投票

您可以在子组件中使用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的小指南

编辑:

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

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()指令后指定的名称,如上例所示)

如您所见,传递几个类只需要一个输入,它只取决于您传递给子的输入变量。

© www.soinside.com 2019 - 2024. All rights reserved.