Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
963 views
in Technique[技术] by (71.8m points)

angular - Angular2 add class to body tag

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

My use case is this:

When I open a modal component (created dynamically) I want the document scrollbar to hide

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would love to comment. But due to missing reputation I write an answer. Well I know two possibilities to solve this issue.

  1. Inject the Global Document. Well it might not be the best practice as I don't know if nativescript etc supports that. But it is at least better than use pure JS.
constructor(@Inject(DOCUMENT) private document: Document) {}

ngOnInit(){
   this.document.body.classList.add('test');
}

Well and perhaps even better. You could inject the renderer or renderer 2 (on NG4) and add the class with the renderer.

export class myModalComponent implements OnDestroy {

  constructor(private renderer: Renderer) {
    this.renderer.setElementClass(document.body, 'modal-open', true);
   }

  ngOnDestroy() {
    this.renderer.setElementClass(document.body, 'modal-open', false);
  }

EDIT FOR 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() {
    this.renderer.removeClass(document.body, 'modal-open');
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...