【问题标题】:Style child component differently when it is in different parent components子组件在不同父组件中时的样式不同
【发布时间】:2019-04-23 14:20:45
【问题描述】:

在 Angular 5 应用程序中,当子组件位于下面的不同父组件列表中时,我希望子组件的样式略有不同。

例如列表组件下卡片的红色背景
列表详情组件下卡片的绿色背景

我想知道我是否可以通过子组件中的scss来做到这一点?因为我认为在子组件本身内部进行跟踪会更容易。

<listing>
  <card />
<listing/>
<listingDetail>
  <card />
</listingDetail>

谢谢。

【问题讨论】:

    标签: angular sass angular-components


    【解决方案1】:

    如果你想影响其子组件的样式,你可以使用 Angular 的 ng-deep

    1.) 在您的 ListingComponent 上,设置 ng-deep 并访问卡片容器类

    @Component({
      selector: 'listing',
      template: `<ng-content></ng-content>`,
      styles: [
        `
          :host ::ng-deep .card-container { background-color: red; }   // Keep in mind, to include :host which means this component as without it, this style will leak out affecting not only its child component class .card-container but also its siblings derived from another component
        `
      ]
    })
    export class ListingComponent {}
    

    2.) 在您的 ListingDetailComponent 上,设置 ng-deep 并访问卡片容器类

    @Component({
      selector: 'listing-detail',
      template: `<ng-content></ng-content>`,
      styles: [
        `
           :host ::ng-deep .card-container { background-color: green; }
        `
      ]
    })
    export class ListingDetailComponent {}
    

    3.) 在您的 CardComponent 上,假设您有一个卡片容器类

    @Component({
      selector: 'card',
      template: `<div class="card-container">Hi I'm Card</div>`,
    })
    export class CardComponent {}
    

    4.) 在您的 AppComponent 上,与您的结构相同

    <listing>
      <card></card>
    </listing>
    
    <listing-detail>
      <card></card>
    </listing-detail>
    

    这是 StackBlitz 演示 link 供您参考


    OR 如果您想控制子组件的样式,可以通过指定 :host-context 和父组件的班级。

    示例:

    1.) 指定我们将用于从子组件(卡片)访问的父类

    <listing class="list-parent">    
      <card></card>
    </listing>
    
    <listing-detail class="list-detail-parent">
      <card></card>
    </listing-detail>
    

    2.) 在您的子组件 (CardComponent) 上,为您的样式指定主机上下文。这样你就可以根据他们的类来设置你的父组件的样式。

    @Component({
      selector: 'card',
      template: `<div class="card-container">Hi I'm Card</div>`,
      styles: [
        `
          :host-context(.list-parent) { background-color: red; }
    
          :host-context(.list-detail-parent) { background-color: green; }
    
        `
      ]
    })
    export class CardComponent {}
    

    【讨论】:

    • 非常感谢您的详尽解释,但我想在子组件中执行此操作,在这种情况下是 组件,以便开发人员在对卡片进行更改时可以注意到组件
    • @Kwinten 更新了我的答案,对应于在子组件中设置父组件的样式,希望对您有所帮助:)
    猜你喜欢
    • 2016-12-15
    • 2017-08-21
    • 2019-05-12
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    • 2023-03-26
    • 2017-09-12
    • 1970-01-01
    相关资源
    最近更新 更多