簡體   English   中英

angular:如何從本地組件訪問應用程序根目錄中的類名?

[英]angular: how can we access the class name in the app-root from local component?

我有三個主頁和多個子頁面,每個子頁面都從父CSS繼承其樣式。

country.routes.ts

 ...
 path: '',
 children: [
    { 
      path: '/country', 
      component: CountryComponent, 
      data: {
        cssClass: 'country',
      },
    },
    { 
      path: ':countryId/city', 
      component: CityComponent ,
      data: {
        cssClass: 'country-city',
      },
    },
    {
      path: ':countryId/fact', 
      component: FactComponent,
      data: {
        cssClass: 'country-fact',
      },
    },
...

像這樣,將CSS類插入到app-root下的div中

index.html(只是粗略的html表示形式)

<app-root>
 <div clas="country/country-fact/country-city">
  <header></header>
  <div>
   <route-outlet>
    <main>
     <!-- content -->
    </main>
   </route-outlet>
  </div>
  <footer></footer>
 </div>
</app-root>

在main.scss中(全局樣式)

country {
  background-color:red;
}
country-city {
  background-color:blue;
}
.country-fact {
  background-color: purple;
}

因為這是有角度的,所以我想利用視圖封裝並在組件聲明器中聲明樣式

country.component.ts

@零件({

 ...
 styles: ['
  :host-context(.country) main{
    background-color:red;
 ','
   :host-context(.country) header{
     display:none;
    }
 '],

國家city.component.ts

@零件({

 ...
 styles: ['
  :host-context(.country-city) main{
    background-color:blue;
 '],

國家fact.component.ts

@零件({

 ...
 styles: ['
  :host-context(.country) main{
    background-color:purple;
 '],

通過閱讀和教程:

我閱讀了本教程 ,因此我通過使用':host'或':host-context(.selector).change-selector來更改/編輯父級的CSS , but it doesn't say I can use the :host-context()在主體或應用程序根目錄級別上。

我嘗試了嵌套:host或`:host {:host-context()},但是都失敗了。

https://blog.angular-university.io/angular-host-context/中 ,它說可以在主體級別使用puseudo類進行選擇,但它不起作用。 我讀了一些其他文章,但找不到鏈接,它說:host-context類似於:host ,帶有選擇器,然后我只能選擇父級的類,而不能在主體級選擇。

問題是main元素不是您要向其應用樣式的組件的一部分

通過閱讀host-context的官方文檔( https://angular.io/guide/component-styles#host-context ),您只能根據組件外部的某些條件將CSS樣式應用於組件內部的元素

以下示例僅在某些祖先元素具有CSS類theme-light的情況下,將背景顏色樣式應用於組件的所有元素。

:host-context(.theme-light) h2 {
  background-color: #eef;
}

因此,要實現您要執行的操作,您需要在具有main標簽的組件內設置這些樣式,或者在您的國家/地區組件內具有main標簽,或者更改規則以在國家/地區組件內定位某個元素(而不是main標簽)

暫無
暫無

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

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