簡體   English   中英

由路由器插座創建時如何將css類應用於組件元素?

[英]How to apply css class to a component element when it's created by router-outlet?

我的 DOM 看起來像這樣:

<app>
    <router-outlet></router-outlet>
    <project>...</project>
</app>

其中project元素由路由器插入。

如何向該元素添加類?

假設您始終希望將類應用於此組件,您可以在組件元數據中使用host

@Component({
  selector:'project',
  host: {
      class:'classYouWantApplied'
  }
})

導致:

<app>
    <router-outlet></router-outlet>
    <project class="classYouWantApplied">...</project>
</app>

使用adjacent sibling selector*通配符來選擇緊跟在router-outlet之后的元素


樣式.css

router-outlet + * {
  /* your css */
}

在此處輸入圖像描述

關鍵是/deep/關鍵字:

    :host /deep/ router-outlet + project {
        display: block;
        border: 10px solid black;
    }

這無需任何額外配置即可工作。

:host /deep/ router-outlet + *用於 Angular 路由器動態創建的任何組件。

2018 年 3 月 5 日編輯:

由於Angular 4.3.0已棄用/deep/ ,因此建議的替代方案是::ng-deep 對此進行了長時間的討論

您可以使用相鄰的兄弟選擇器

router-outlet + project { ... }

https://developer.mozilla.org/en/docs/Web/CSS/Adjacent_sibling_selectors

但前提是@drewmoore 的方法不適用。

您可以使用HostBinding執行此操作,這實際上與使用已經提到的host屬性相同,盡管該方法使用默認列表規則引發 TSLint 錯誤。

在要應用類的組件中:

import { Component, HostBinding, Host (optional for typing) } from '@angular/core';

@Component({...})
export class GiveMeAClassComponent {
    @HostBinding('class.some-class') someClass: Host = true;
    ...
}

然后在您的根styles.scss文件中,您可以添加以下內容:

.some-class {
    // Styles in here will now be applied to your GiveMeAClassComponent at a root level
}
<app>
  <div class="your css class">
   <router-outlet></router-outlet>
</div>
</app>

這對我有用

如果您需要有條件地添加一個類,您可以從組件中以編程方式添加它:

constructor(private renderer: Renderer2, private elemRef: ElementRef) {
  if(someCondition){
    renderer.addClass(elemRef.nativeElement, 'myClass');
  }
}

目前,Angular 6 建議我使用 @HostBindings 和 @HostListeners 而不是 host 屬性:

export class ProjectComponent {
  @HostBinding('class') classes = 'classYouWantApplied';
}

由於路由器在 router-outler 元素之后注入組件,如果我們想使用相同的規則集設置所有注入組件的樣式,則以下規則可能會有所幫助。

css "+" 運算符選擇特定類型的第一個兄弟元素,而星號 (*) 用作通配符以選擇 router-outlet 的任何第一個兄弟元素

router-outlet + * {
  // your rules
}

我創建了一個可以根據需要進行修改的RouterOutletHelperDirective

您的用例可能會有所不同,但對我來說:

  • 我需要在每個 router-outlet 生成的項目上設置一組默認的類
  • 我需要根據某些條件(例如ActivatedRoute數據)阻止此默認設置。

您可以這樣使用它(該類是可選的):

<router-outlet routerOutletHelper
               [routerOutletHelperClass]="'blue-border'"></router-outlet>

然后創建指令,將其添加並導出到您的應用程序模塊。

import { Directive, ElementRef, Renderer2, Input } from "@angular/core";
import { RouterOutlet } from "@angular/router";
import { Subscription } from "rxjs";

@Directive({
    selector: 'router-outlet[routerOutletHelper]'
})
export class RouterOutletHelperDirective
{
    constructor(private routerOutlet: RouterOutlet,
                private element: ElementRef<HTMLElement>,
                private renderer: Renderer2) { }

    subscription = new Subscription();

    @Input('routerOutletHelperClass')
    customClassName: string | undefined;

    ngOnInit() 
    {
        this.subscription.add(this.routerOutlet.activateEvents.subscribe((_evt: any) => {

            // find the component element that was just added
            const componentElement = this.element.nativeElement.nextSibling;

            // add a custom class
            if (this.customClassName) 
            {
                this.renderer.addClass(componentElement, this.customClassName);
            }

            // add my default classes, unless the activated route data 
            // (specified in module routing file) has { addDefaultClasses: false }
            if (this.routerOutlet.activatedRouteData && this.routerOutlet.activatedRouteData.addDefaultClasses !== false)
            {
                // these are my application's default classes (material / theming)
                // (an additional data parameter could be 'darkTheme: boolean')
                this.renderer.addClass(componentElement, 'mat-typography');
                this.renderer.addClass(componentElement, 'rr-theme-light');
            }
        }));
    }

    ngOnDestroy()
    {    
        this.subscription.unsubscribe();
    }
}

對我來說,它有助於將路由器插座包裝到另一個容器中。

<div class="classYouWantApplied">
  <router-outlet>
</div>

像這樣,您可以將類應用於周圍的容器。

添加主機類名稱,它將向組件添加一個類,然后使用相鄰來定位元素。

@Component({
  selector:'project',
  host: {
      class:'Project-wrapper'
  }
})

現在使用與角度相鄰的 CSS

::ng-deep to target it:
::ng-deep .Project-wrapper {}

這很簡單,假設在您的應用程序組件中,您有一個
<router-outlet ></router-outlet>

在這個路由器插座中,您有一個名為<app-product-detail></app-product-detail>的路由組件

並且您想更改 app.component.html 中的視圖。

首先在組件<app-product-detail>添加以下代碼段:

@Component({


selector: 'app-product-detail',
  host: {
    class:'Project-wrapper'
},
  templateUrl: './product-detail.component.html',
  styleUrls: ['./product-detail.component.css']
})```

class= '可以是任何名字'

在 app.component.css 中添加以下代碼段:

    ::ng-deep .Project-wrapper { 
width: 85%;
        background-color: aqua;
    }

暫無
暫無

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

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