How can I add a class to the body tag without making the body as the app selector and using host binding?
I tried the using the Renderer but it changes the whole body
Angular 2.x bind class on body tag
I'm working on a big angular2 app and changing the root selector will impact a lot of code, I will have to change a lot of code
私の使用例は次のとおりです:
モーダルコンポーネント(動的に作成)を開くときに、ドキュメントのスクロールバーを非表示にしたい
ベストアンサー1
コメントしたいのですが、評判がないため回答を書きます。この問題を解決するには 2 つの可能性があると思います。
- グローバル ドキュメントを挿入します。nativescript などがこれをサポートしているかどうかはわかりませんが、これはベスト プラクティスではないかもしれません。ただし、少なくとも純粋な JS を使用するよりはましです。
constructor(@Inject(DOCUMENT) private document: Document) {}
ngOnInit(){
this.document.body.classList.add('test');
}
まあ、おそらくもっと良いでしょう。レンダラーまたはレンダラー 2 (NG4 の場合) を挿入し、レンダラーを含むクラスを追加できます。
export class myModalComponent implements OnDestroy {
constructor(private renderer: Renderer) {
this.renderer.setElementClass(document.body, 'modal-open', true);
}
ngOnDestroy(): void {
this.renderer.setElementClass(document.body, 'modal-open', false);
}
}
ANGULAR4 用に編集:
import { Component, OnDestroy, Renderer2 } from '@angular/core';
export class myModalComponent implements OnDestroy {
constructor(private renderer: Renderer2) {
this.renderer.addClass(document.body, 'modal-open');
}
ngOnDestroy(): void {
this.renderer.removeClass(document.body, 'modal-open');
}
}