【问题标题】:Pass class to children component host将类传递给子组件主机
【发布时间】:2018-09-23 18:02:18
【问题描述】:

我习惯了 React 方法,我基本上可以在任何地方注入任何东西。

我在 Angular 中有一个愚蠢的 Buttonapp-button 组件。它是 inline-block(:host 类),所以它的宽度取决于内容。在这种情况下,我不能覆盖它的参数,如display: block 或设置宽度。我可以通过为每个参数添加新的@Input[display][width])手动完成,但这并不是很好。

我想要的行为是该组件上的输入/指令,以向子组件内部提供显式注入类。

在 React 中,我只需添加带有类名的 prop 并分配它或传递一些内联样式,具体取决于我使用的样式系统。

有没有办法/lib/util 来处理这个问题?

【问题讨论】:

  • 您能否看看my answer,并考虑将其作为可接受的,因为它更易于代码维护并且不建议解决明确设置的行为?同样根据upvotes,它实际上对当前读者更有帮助。

标签: css angular


【解决方案1】:

由于 Angular 的 ViewEncapsulation 你不能像 React 那样做。

最好的办法是直接设置按钮:host 元素的样式。这样你就可以用父组件中定义的类来覆盖它。

app-button.component.ts

import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-button',
  template: `
    I am red by default
  `,
  styles: [`
  :host {
    background-color: red;
  }
  `]
})
export class ButtonComponent {}

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
  <app-button class="button"></app-button>
  `,
  styles: [
    `.button { 
       background-color: blue; 
     }
    `
  ]
})
export class AppComponent  {}

Live demo

【讨论】:

    【解决方案2】:

    今天还有其他几种可能性:

    :host-context(.some-class-name) 这可以让你对一些外部类做出反应

    ::ng-deep css 表达式{ xx } 这样您就可以在父级中定义一个在其子级中可用的类。


    示例:

    parent.component.html

    <app-button class="theme-blue"> my button </app-button>
    

    button.component.css

    :host-context(.theme-blue) button {
       background-color: blue;
    }
    

    不妨看看这个很好的指南: https://alligator.io/angular/styles-between-components-angular/

    【讨论】:

    • ng-deep 已弃用:angular.io/guide/component-styles
    • +1host-context使用
    【解决方案3】:

    您不应该为父组件中的子组件元素编写 CSS 规则,因为 Angular 组件是一个自包含的实体,它应该明确声明可供外部世界使用的内容。如果将来子布局发生变化,则分散在其他组件的 SCSS 文件中的子组件元素的样式很容易损坏,从而使您的样式非常脆弱。这就是 ViewEncapsulation 在 CSS 中的用途。否则,如果您可以从面向对象编程中的任何其他类为某个类的私有字段分配值,那将是相同的。

    因此,您应该做的是定义一组可以应用于子宿主元素的类,并实现子元素如何响应它们。

    从技术上讲,可以这样做:

    // child.component.html:
    <span class="label-1"></span>
    
    // child.component.scss:
    :host.child-color-black {
        .label-1 {
            color: black;
        }
    }
    
    :host.child-color-blue {
        .label-1 {
            color: blue ;
        }
    }
    
    // parent.component.html:
    <child class="child-color-black"></child>
    <child class="child-color-blue"></child>
    

    换句话说,您使用 Angular 提供的 :host 伪选择器 + 一组 CSS 类来定义子组件本身中可能的子样式。然后,您可以通过将预定义的类应用于 &lt;child&gt; 宿主元素来从外部触发这些样式。

    【讨论】:

      猜你喜欢
      • 2018-04-30
      • 2017-12-02
      • 2017-12-26
      • 2020-01-14
      • 2019-04-12
      • 1970-01-01
      • 2022-11-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多