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

14

我正在尝试对自定义组件的子元素应用样式。

选择器:

<custom-component-example></custom-component-example>

在custom-component-example.html内部:

<button>
    <ng-content></ng-content>
</button>

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

<custom-component-example style="color: green">some text</custom-component-example>

或者像这样:

<custom-component-example [ngStyle]="{'color': green}">some text</custom-component-example>

按钮文本不会变成绿色。样式可以是任何东西(例如字重或大小或其他任何内容)。

我也尝试了此主题的解决方案:

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

但是这也不能应用于子元素(例如上面示例中的按钮)。

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

提前致谢。


由于它是 Angular 2+,所以在定义自定义组件时应将其分配给 CSS 文件或内联样式表。这些样式可能是静态的。我们为什么要尝试在运行时注入它呢? - Ashokan Sivapragasam
我猜,Angular 2+中的每个组件都应该是自包含的。 - Ashokan Sivapragasam
我认为这两种方法都没有问题,你可以检查一下按钮的样式是从哪里来的,可能会有样式权重或优先级的问题。当你编写style属性时,它与angular/javascript是独立的,只是HTML和CSS。 - 3960278
5个回答

12
你不应该从父元素中更改子元素的样式,相反,你应该这样做:
在父元素上应用一个类(比如说green-button)。 在子元素的CSS中,你需要检查它的父元素是否有一个绿色按钮的类,如果有,则应该更改它的颜色。
在子元素的CSS文件中 ->
:host-context(.green-button) button{
color : green
}

不应该将样式从父组件传递给子组件,因为这会破坏 Angular 傲视的 ViewEncapsulation 特性。

参考资料:链接

此外,子组件应该负责按钮的外观。父组件应该只关心自己。如果将来您要给父组件添加两个子组件,那么管理哪个样式传递给哪个子组件将会很困难。

使用这种方法,修改样式不仅容易而且可管理性强。

如果我能帮到您,请点赞并标记为已解决。谢谢。


1
你好,我使用了你提供的解决方案来解决我的问题。它运行得很好,我也尝试了其他一些解决方案,但是无法使它们正常工作。也感谢你的解释。 - Niek Jonkman

5
尝试将 styles 更改为 [styles]custom-component-example.html
<button [ngStyle]="styles">
    <ng-content></ng-content>
</button>

custom-component-example.ts

@Input() styles: any = {};

使用:

<custom-component-example [styles]="{color: green}">some text</custom-component-example>

3

您需要使用@Input()将样式属性传递给子组件,例如

您的子组件HTML代码应如下所示

<div [className]="tableCss">
</div>

您的子组件ts文件代码应该如下所示:
@Input() tableCss: string;

您的父组件应该看起来像:
<app-list [tableCss]="'table-responsive table-borderless table-grid mt-4 border-top border-primary'"></app-list>

0

尝试这个:

  1. 在您的模板文件中添加一个组件类,例如下面的示例(class='toggle-button')。

<custom-component-example class="toggle-button"> 按钮名称 </custom-component-example>

  • 在您的scss文件中使用::ng-deep来为此类添加样式,并将!important添加到该参数。

     ::ng-deep .toggle-button { .switch-btn {
     width: 80px !important;
     height: 40px !important;}}
    
  • *"switch-btn"类是父组件中的一个类。


    0

    如果您想使用输入和样式,而无需深度选择css,就像这样:

    a > b > c {
        color: green;
    }
    

    将这个类改为这样:

    class CustomComponentExample {
        @Input() styles;
    }
    

    为此输入设置样式:

    <custom-component-example [styles]="{'color': green}">some text</custom-component-example>
    

    在你的组件中使用这个属性:
    <button [ngStyle]="styles">
        <ng-content></ng-content>
    </button>
    

    网页内容由stack overflow 提供, 点击上面的
    可以查看英文原文,
    原文链接