2017-06-14 100 views
2

有沒有辦法在Angular2中動態添加樣式表url或<style></style>如何在Angular 2中動態添加樣式表?

例如,如果我的變量是isModalOpenedtrue,我想爲根組件之外的少數元素添加一些CSS。像bodyhtml

有可能與DOM或jQuery來做到這一點,但我想用角2

可能這樣做?

感謝

+0

看看NgClass https://angular.io/api/common/NgClass –

+0

@YakovFain就我而言,我無法訪問身體。所以我不能爲它添加ng-class屬性。 – Steffi

回答

0

我不知道,你可以把它做的身體或HTML,但你可以做到這一點到根組件。

  • 創建注入到根組件
  • 服務讓服務有一個國家(可能是BehaviorSubject
  • 訪問該服務,當isModalOpened改變
  • 在根組件改變狀態,你會正在觀察這個並更改組件參數值
  • 在根組件html中,可以根據組件參數值更改類值

更新:從內部組件設置背景顏色。

app.component.css

.red{ 
    background: red; 
} 

.white{ 
    background: white; 
} 
.green{ 
    background: green; 
} 

app.component.html

<div [ngClass]="backgroundColor" ></div> 

app.component.ts

constructor(private statusService: StatusService) { 
    this.subscription = this.statusService.getColor() 
    .subscribe(color => { this.backgroundColor = color; }); 
} 

status.service.ts

private color = new Subject<any>(); 
public setColor(newColor){ 
    this.color.next(newColor); 
} 
public getColor(){ 
    return this.color.asObservable(); 
} 

child.component.ts

export class ChildComponent { 
    constructor(private statusService: StatusService) {} 

    setColor(color:string){ 
     this.statusService.setColor(color); 
    } 
} 

所以每當我們稱之爲的setColor並傳遞一個顏色變量如 '紅色', '綠色' 或 '白色' 根組件的背景相應地改變。

+0

你能舉個例子嗎? – Steffi

+0

將創建一個plnkr – Skeptor

0

把你所有的HTML代碼中的自定義指令 - 讓我們把它ngstyle ...

您ngstyle添加到您的網頁使用的指令標籤,在我們的例子:

<ngstyle><ngstyle> 

但我們也使用ng將邏輯附加到您的指令 - 如果您可以打開或關閉它的話...

<ngstyle ng-if="!isModalOpened"><ngstyle> 

現在,如果你的「isModalOpened」設置爲一個範圍在您的控制器是這樣的:

$scope.isModalOpened = false; //or true, depends on what you need 

...您可以切換它應該在切換您的指令真的還是假的許多不同的方法並關閉。

1

您可以動態創建<style>標籤是這樣的:

ngOnInit() { 
    const css = 'a {color: pink;}'; 
    const head = document.getElementsByTagName('head')[0]; 
    const style = document.createElement('style'); 
    style.type = 'text/css'; 
    style.appendChild(document.createTextNode(css)); 
    head.appendChild(style); 
} 
相關問題