简体   繁体   中英

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.

在此处输入图像描述

From what I have read this would be done with jquery but it is no longer recommended. Additionally I read that the ideal would be to use the class "Renderer2" So my query would be:

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.

 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

If you're looking for an angular solution specifically:

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

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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