如何将样式应用于 Angular 中的自定义组件内容?

Nie*_*man 7 html javascript css angular

我正在尝试将样式应用于自定义组件的子组件。

选择器:

<custom-component-example></custom-component-example>
Run Code Online (Sandbox Code Playgroud)

在 custom-component-example.html 中:

<button>
    <ng-content></ng-content>
</button>
Run Code Online (Sandbox Code Playgroud)

如果我要使用这样的样式:

<custom-component-example style="color: green">some text</custom-component-example>
Run Code Online (Sandbox Code Playgroud)

或者像这样:

<custom-component-example [ngStyle]="{'color': green}">some text</custom-component-example>
Run Code Online (Sandbox Code Playgroud)

按钮文本不会变绿。样式可以是任何东西(例如字体粗细或大小或任何真正的东西)。

我也尝试过这个主题的解决方案:

将样式传递给组件的最佳方式

但这也不适用于子元素(上例中的按钮)。

如何传递任何给定的样式并将其应用于子元素,在示例的情况下,我将如何传递样式(通过 custom-component-example 选择器)并将其应用于按钮和按钮的文本?

提前致谢。

ish*_*ava 7

你永远不应该改变父元素的子样式,而你应该这样做:

将一个类应用于父类(假设为绿色按钮)。在孩子的 css 中,你需要检查我的父母是否有一个类绿色按钮,如果是,那么它应该改变它的颜色。

在孩子的 css 文件中 ->

:host-context(.green-button) button{
color : green
}
Run Code Online (Sandbox Code Playgroud)

你不应该本质上将样式从父级转移到子级,因为它破坏了 Angular 引以为豪的 ViewEncapsulation 优点。这里有一些参考。:链接

此外,子组件应该负责按钮的外观。父母应该关心自己。以后如果要给父母生两个孩子,就很难管理什么风格传给什么孩子了。使用这种方法,改变风格不仅容易而且易于管理。

如果我能够提供帮助,请投票并标记为已解决。干杯。


Sri*_*kar 5

尝试改变styles成[styles]

自定义组件示例.html

<button [ngStyle]="styles">
    <ng-content></ng-content>
</button>
Run Code Online (Sandbox Code Playgroud)

自定义组件示例.ts

@Input() styles: any = {};
Run Code Online (Sandbox Code Playgroud)

使用,

<custom-component-example [styles]="{color: green}">some text</custom-component-example>
Run Code Online (Sandbox Code Playgroud)