将类传递给子组件宿主

8

我习惯于使用React的方法,可以将任何内容注入到任何地方。

我有一个愚蠢的Buttonapp-button组件在Angular中。它是内联块(:host类),因此其宽度取决于内容。在这种情况下,我无法覆盖其参数,如display:block或设置宽度。我可以通过添加新的参数([display], [width])来手动执行,但这不太好。

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

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

是否有任何方法/lib/util来解决这个问题?


你能否看一下我的回答,并考虑将其设为已接受的答案,因为它更易于维护代码,而且不建议绕过明确设置的行为?此外,根据点赞数,它实际上对当前读者更有帮助。 - Alexander Abakumov
3个回答

4

你不应该在父组件中为子组件元素编写CSS规则,因为Angular组件是一个自包含实体,应该明确声明对外可用的内容。如果将子布局更改为未来,那么分散在其他组件 SCSS 文件中的子组件元素样式很容易破坏,从而使您的样式非常脆弱。这就是CSS情况下需要使用 ViewEncapsulation 的原因。否则,在面向对象编程中,这将与从任何其他类中分配私有字段的值相同。

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

从技术上讲,可以按以下方式完成:

// 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类来定义子组件本身可能具有的子样式。然后,通过将预定义类应用于<child>主机元素,您可以从外部触发这些样式。


3
由于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  {}

演示现场


3
今天有几种其他可能性: :host-context(.some-class-name) 这样可以对某个外部类进行反应
::ng-deep css-expression{ 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/

该指南涉及与 Angular 组件间样式有关的技术内容。

1
ng-deep已被弃用:angular.io/guide/component-styles - derpedy-doo
1
+1 for the use of host-context - Nic Laforge

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