[英]How should a parent style a child component for Angular? I'd like a good solution that won't be deprecated
当我需要为新用途而稍微更改组件时,我研究了转置和多插槽转置以及在组件周围添加HTML的情况,但是仍然有一些情况需要更改组件的内部样式。
Components should be self contained and programmed so they don't require refactoring whenever a new use is needed. 组件应自包含并进行编程,因此在需要新的用途时就不需要重构。
One solution is to add a class to the parent using ng-class, and then use regular css rules to style the child: one set of rules that requires the class to be on the parent div, and another set that doesn't require the class to be on the parent div. 一种解决方案是使用ng-class向父级添加一个类,然后使用常规的CSS规则为子级设置样式:一套要求该类位于父div上的规则,另一套不需要该子类的规则。类位于父div上。
Example css: 示例CSS:
.my_class {Normal styling}
.my_parent_div_class .my_class {Special styling goes here}
You can pass a style in as an input, and then set it in the template with [ngStyle]. 您可以传入样式作为输入,然后使用[ngStyle]在模板中进行设置。
So for a simple example i'll show how to do this with a background color. 因此,作为一个简单的示例,我将展示如何使用背景色执行此操作。
customComponent.html customComponent.html
<div [ngStyle]="{'background-color': data?.backgroundColor }">
<p> the background color will be set from an input </p>
</div>
customComponent.ts customComponent.ts
@Input('data')
data: {
backgroundColor: string;
};
parent.html parent.html
<customComponent [data]="{backgroundColor: 'grey'}"></customComponent>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.