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

时间:2019-06-20 10:04:46

标签: javascript html css angular

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

选择器:

<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>

按钮文本不会变为绿色。样式可以是任何东西(例如,字体粗细或大小或其他任何东西)。

我还尝试了该主题的解决方案:

Best way to pass styling to a component

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

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

谢谢。

5 个答案:

答案 0 :(得分:2)

您永远不应更改父级的子级样式,这是您应该做的:

将一个类应用于父级(假设是绿色按钮)。 在孩子的css中,您需要检查我的父母是否有类绿色按钮,如果是,则应该更改其颜色。

在孩子的css文件中->

:host-context(.green-button) button{
color : green
}

您不应将样式从父项本质转换为子项本质,因为这会破坏Angular引以为傲的ViewEncapsulation优势。 这是一些参考。 :Link

此外,子组件应负责其按钮的外观。父母应该关心自己。将来,如果您将有两个孩子带给父母,将很难管理将哪种样式传递给哪个孩子。 使用这种方法,更改样式不仅简单而且易于管理。

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

答案 1 :(得分:0)

我正在使用这种方法来设计我的组件的样式。但是我使用的是scss,因此如果您想拥有像我这样的嵌套样式,就必须使用scss

custom-component-example {
  color: red;
  & > div {
    font-size: 16px;
 }
}

答案 2 :(得分:0)

您需要使用@Input()

一样将style属性传递给子组件。

您的子组件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>

答案 3 :(得分: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>

答案 4 :(得分:0)

尝试将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>
相关问题