简体   繁体   English

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

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

Currently I have defined through bootstrap the following template of my component:目前我已经通过引导程序定义了我的组件的以下模板:

<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>

I want to implement that when the browser screen is reduced to less than 767.98px it will center the question lines.我想实现,当浏览器屏幕缩小到小于 767.98px 时,它会将问题行居中。

在此处输入图像描述

From what I have read this would be done with jquery but it is no longer recommended.根据我的阅读,这将使用 jquery 完成,但不再推荐。 Additionally I read that the ideal would be to use the class "Renderer2" So my query would be:此外,我读到理想的情况是使用 class “Renderer2” 所以我的查询是:

That part of the documentation on Renderer2 will allow me to make the sensing of the screen size since in some way there must be a kind of media query which detects when the screen is less than 767.98px and then adds the bootstrap classes that I defined so that the divs i wish to focus on. Renderer2 上的那部分文档将允许我感知屏幕尺寸,因为在某种程度上必须有一种媒体查询来检测屏幕何时小于 767.98px,然后添加我定义的引导类我希望重点关注的 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>

You can use VanillaJS你可以使用 VanillaJS

If you're looking for an angular solution specifically:如果您正在寻找 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 is the key here HostListener 是这里的关键

Decorator that declares a DOM event to listen for, and provides a handler method to run when that event occurs.声明要侦听的 DOM 事件并提供在该事件发生时运行的处理程序方法的装饰器。 Angular HostListener Docs Angular HostListener 文档

<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>

Also if you're using Angular Universal for SSR, this approach wont throw any errors about window is not defined during server parsing and populating the dynamic HTML此外,如果您将Angular Universal用于 SSR,则此方法不会引发有关window is not defined任何错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM