首页 文章

将类传递给子组件主机

提问于
浏览
2

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

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

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

在React中,我只需添加类名称的prop,并指定它或传递一些内联样式,具体取决于我正在使用的样式系统 .

是否有任何方式/ lib / util来处理这个问题?

3 回答

  • 0

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

  • 0

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

    :host-context(.some-class-name)这使您可以对某些外部类做出反应

    :: ng-deep css-expression 这样你就可以在父类中定义一个可以在它的子节点中使用的类 .


    Example:

    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/

  • 1

    您不应该为父组件中的子组件元素编写CSS规则,因为Angular组件是一个自包含的实体,应该明确声明可用于外部世界的内容 . 如果子布局将来发生更改,那么子组件元素的样式将分散在其他组件中' SCSS files could easily break, thus making your styling very fragile. That' s在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 CSS类集提供的 :host 伪选择器来定义子组件本身中可能的子样式 . 然后,您可以通过将预定义的类应用于 <child> host元素来从外部触发这些样式 .

相关问题