簡體   English   中英

如何在子組件-Angular 2中對根組件的css類進行控制?

[英]How to ovveride the css class of root component in its child component - Angular 2?

我在angular 2應用程序中有3個組件class="container-fluid content"是app.component.html中的CSS類。 class="container-fluid content"是其他組件的默認CSS。 現在,我想在detail組件中設置background-color:blue 我試圖像這樣的styles:['.container-fluid content{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;">它適用於兩個組件。 如何覆蓋詳細組件中的class =“ container-fluid content”?

 //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;
}
}

在子組件中,您可以將此參數添加到@Component。

child-component.component.ts

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

child-component.component.css

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

您可以參考這一面以獲得更多信息:

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

您是否嘗試過主機綁定並在那里添加新類?

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

在第二個組件中,只需將其打開onInit?

ngOnInit() {
    this.blue = true;
} 

另一種方法可能是在組件定義中,您可以添加以下行:

  host: {'class': 'blueClass'} 

然后您在CSS中完成其余的CSS工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM