简体   繁体   English

父母应该如何为Angular设置子组件的样式? 我想要一个不会被淘汰的好的解决方案

[英]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.

相关问题 应用于Angular 2中的父组件的子样式? - Child style applying to parent component in Angular 2? Angular 从父组件更改子组件样式但不是全局更改 - Angular change child component style from parent component but not globally Angular 如何 position 将子组件放在中心而不向父组件中的 td 元素添加样式 - Angular how to position the child component in center without adding style to td element in parent component 从父组件到子组件Angular2 / 4触发悬停样式 - Trigger hover style from parent to child component Angular2/4 如何从父组件设置递归嵌套子组件的样式 - How to style recursively nested child component from parent component 如何在不影响 React Native 中的子组件的情况下设置父组件的样式 - How to style parent component without affecting child component in React Native 如何通过父级将css应用于角度的子组件 - How to apply css by parent to child component in angular 如何在没有 ng-deep 的情况下从父 SCSS 设置子组件的样式? - How do I style child component from parent's SCSS without ng-deep? 当我们有 2 个子组件时,如何将样式从父组件应用到子组件 - How to apply style to child component from parent component when we have 2 child component 如何从父组件的 CSS 文件中设置子组件的样式? - How to style child components from parent component's CSS file?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM