如何在其子组件中使用根组件的css类 - Angular 2?

时间:2017-06-02 11:30:58

标签: html css angular angular-components

我在角度2应用程序中有3个组件。class="container-fluid content"是app.component.html中的css类。此class="container-fluid content"是其他组件的默认css。现在我想在详细信息组件中设置background-color:blue。我试着像这样设置detail.component.ts styles:['.container-fluid content{background-color: blue;}']它没有用。如果我在app.component.html中设置如此<div class="container-fluid content" style="background-color: blue;">它适用于这两个组件。如何覆盖这个类=&#34;容器流体内容&#34;详细部分?

 //my project structure

app
  - app.component.html
  -app.component.ts
- welcome
  -welcome.component.html
  -welcome.component.ts
- detail
  -detail.component.html
  -detail.component.ts

//app.component.html
<div class="container-fluid content">
    <router-outlet></router-outlet>
  </div>
  <app-footer></app-footer>
</div>

//welcome.component.html
<h1>welcome page heading</h1>
<div fxLayout="row" fxLayoutWrap  style="padding-bottom: 25px; 
 padding-top: 25px;  margin: auto;justify-content: center" >  
<md-card>
          <md-card-content>
            <h1></h1>
            <h2></h2>
          <h2>
            </h2>
          </md-card-content>
          </md-card> 
        </div>

//detail.component.html
<h1>Details page heading</h1>
<div fxLayout="row" fxLayoutWrap  style="padding-bottom: 25px; 
 padding-top: 25px;  margin: auto;justify-content: center" >  
<md-card>
          <md-card-content>
            <h1></h1>
            <h2></h2>
          <h2>
            </h2>
          </md-card-content>
          </md-card> 
        </div>
//detail.component.ts
import { OnInit, Component } from '@angular/core';
import { DetailService } from '../detail/detail.service'; 
import { HostBinding} from '@angular/core';

@Component({

  providers: [DetailService ]
  templateUrl: './detail.component.html',
  styles: ['h3 {margin:5px}'] 

})

export class DetailComponent implements OnInit {

 @HostBinding('class.blueClass') blue: boolean = false;

  constructor( private _detailService: DetailService ) { }

  ngOnInit() {

this.blue = true;
}
}

2 个答案:

答案 0 :(得分:1)

在子组件中,您可以将此参数添加到@Component。

儿童component.component.ts

@Component({ selector: 'child-component', templateUrl: 'child-component.component.html', styleUrls: ['child-component.component.css'] encapsulation: ViewEncapsulation.None })

儿童component.component.css

.container-fluid content{background-color: blue;}

您可以参考此方面以获得更多信息:

https://blog.thoughtram.io/angular/2015/06/29/shadow-dom-strategies-in-angular2.html

答案 1 :(得分:0)

您是否尝试过使用主机绑定并在那里添加新课程?

 @HostBinding('class.blueClass') blue: boolean = false;

在第二个组件中只需在onInit上切换它?

ngOnInit() {
    this.blue = true;
} 

另一种方式可能是在组件定义中,您可以添加以下行:

  host: {'class': 'blueClass'} 

然后你用css完成其余的css工作。