如何在不使用 Jquery 的情况下将 class 添加到 DOM 元素 - Angular 6

How to add a class to a DOM element without using Jquery - Angular 6

目前我已经通过bootstrap定义了我的组件的以下模板:

<div class="container">

  <div class="row my-4">
    <div class="col-md-12 d-flex justify-content-center">
      <h2> EVALUACIÓN DE {{ curso }} </h2>
    </div>
  </div>

  <div class="row">
    <div class="col-md-9">
      <h4>Pregunta 1 de 20 </h4>
      <p>¿Cúal de las siguientes alternativas es correcta? </p>
    </div>
    <div class="col-md-3 d-flex align-items-center" id="icono-reloj">
      <img class="mx-2" src="/assets/img/alarm-fill.svg" alt="" width="24" height="24" title="timer"> <span class="mx-3">0:20</span>
    </div>
  </div>

  <div class="row">
    <div class="col-md-12">
      <div class="list-group" ngFor="let alternativa of alternativas">
        <p class="list-group-item list-group-item-action" (click)="avanzar()">este es un ejemplo de una alternativa ...</p>
      </div>
    </div>
  </div> 
</div>

我想实现当浏览器屏幕缩小到小于 767.98px 时它将问题行居中。

据我所知,这可以用 jquery 完成,但不再推荐这样做。另外我读到理想的是使用 class "Renderer2" 所以我的查询是:

Renderer2 上的那部分文档将使我能够感知屏幕尺寸,因为在某种程度上必须有一种媒体查询来检测屏幕何时小于 767.98 像素然后添加我定义的 bootstrap classes 以便我希望关注的 div。

function windowResizeFunc() {

    function reportWindowSize() {
    
     let h = window.innerHeight;
     let w = window.innerWidth;

      console.log("Current Width: "+ w);
      
         if( w < 600 ) {
         document.getElementById("yourElementId").classList.add("center");
         } else {
                  document.getElementById("yourElementId").classList.remove("center");
         }
    }
      
    window.onresize = reportWindowSize;
}


windowResizeFunc();
#yourElementId {
border: 1px solid #5599cc;
}
.center{ 
  text-align: center;
}
<div id="yourElementId">Some text</div>

你可以使用 VanillaJS

如果您要专门寻找 angular 解决方案:

import {
  Component,
  OnInit,
  HostListener,
  ViewChild,
  ElementRef,
} from "@angular/core";

@Component({
  selector: "app-header",
  templateUrl: "./header.component.html",
  styleUrls: ["./header.component.scss"],
})
export class HeaderComponent implements OnInit {
  currentWindowWidth: number;
  isMobile: boolean;

  @ViewChild("control") control: ElementRef;

  constructor() {}

  ngOnInit() {}

  @HostListener("window:resize", ["$event"])
  public onResize(window) {
    this.isMobile = window.currentTarget.innerWidth < 993 ? true : false;
    this.toggleMobileClasses(this.control.nativeElement, this.isMobile)
  }

  @HostListener("window:load", ["$event"])
  public onLoad(window) {
    this.isMobile = window.currentTarget.innerWidth < 993 ? true : false;
  }

  toggleMobileClasses(targetElement: HTMLElement, isMobile) {
    isMobile ? targetElement.classList.add('text-center') : targetElement.classList.toggle('text-center');
  }

}

HostListener 是这里的关键

Decorator that declares a DOM event to listen for, and provides a handler method to run when that event occurs. Angular HostListener Docs

<div #control class="container">

  <div class="row my-4">
    <div class="col-md-12 d-flex justify-content-center">
      <h2> EVALUACIÓN DE {{ curso }} </h2>
    </div>
  </div>

  <div class="row">
    <div class="col-md-9">
      <h4>Pregunta 1 de 20 </h4>
      <p>¿Cúal de las siguientes alternativas es correcta? </p>
    </div>
    <div class="col-md-3 d-flex align-items-center" id="icono-reloj">
      <img class="mx-2" src="/assets/img/alarm-fill.svg" alt="" width="24" height="24" title="timer"> <span class="mx-3">0:20</span>
    </div>
  </div>

  <div class="row">
    <div class="col-md-12">
      <div class="list-group" ngFor="let alternativa of alternativas">
        <p class="list-group-item list-group-item-action" (click)="avanzar()">este es un ejemplo de una alternativa ...</p>
      </div>
    </div>
  </div> 
</div>

此外,如果您使用 Angular Universal 作为 SSR,此方法不会在服务器解析和填充动态 window is not defined 期间抛出任何有关 window is not defined 的错误 HTML