A guide on including a class to a DOM element in Angular 6 without relying on Jquery

Currently, I have created a component template using Bootstrap that looks like this:

<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 am looking to implement a feature where the question lines will be centered when the browser screen is resized to less than 767.98px.

https://i.stack.imgur.com/1VRND.png

After researching, it seems that achieving this with jQuery is no longer recommended. It is suggested to use the "Renderer2" class instead. So, my question is:

Does the documentation on Renderer2 provide a way to detect the screen size and apply specific Bootstrap classes based on that, such as centering the divs in question when the screen width is less than 767.98px?

Answer №1

In search of a specific angular solution:

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');
  }

}

The significance lies in the HostListener

Decorator that specifies a DOM event to watch for and assigns a method to execute 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>

If utilizing Angular Universal for Server Side Rendering, this method will not trigger any errors regarding window is not defined while rendering and filling dynamic HTML content.

Answer №2

function resizeWindow() {

    function reportWindowSize() {
    
     let height = window.innerHeight;
     let width = window.innerWidth;

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


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

You have the option to utilize VanillaJS

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporating full-screen viewing in the browser, these websites provide a seamless user experience with a "learn more" button strategically placed at the bottom. This button effortlessly

Have you ever noticed how websites like Heroku.com and dropbox.com automatically display a full-screen homepage tailored to your browser size? They have a clever button at the bottom that smoothly scrolls you down the page for more information. Have you wo ...

Suggestions for enhancing the functionality of this code by incorporating an additional dynamic chained selection box

Currently, I am utilizing a plugin offered by CSS-Tricks to create two chained select boxes using PHP, jQuery, and MySQL. I am contemplating the idea of introducing an additional box that will be dependent on the selections made in the first and second box ...

Tips for maintaining i18n locale slugs and ensuring i18n consistency when reloading in Next.js

I'm currently utilizing next-translate. The default recognition of my routes is as follows: /about <--- /de/about /es/about However, I would like to set a specific locale for all paths: /en/about <--- /de/about /es/about Below is ...

retrieve a subdocument from an array in MongoDB

In my MongoDB database, I have the following data structure: {doc: { array_doc:[....//many documents]} } Currently, I am working with Mongoskin in MongoDB 2.2 with Node.js 0.8. var code_doc='HSKD41814541211'; var db = mongo.db(perm+"@127.0 ...

Can integers be used as keys in a JavaScript object's storage?

Currently, I am in the process of creating a JSON index file to serve as a database index for a javascript application that is currently under development. The structure of my index will resemble the following: { "_id": "acomplex_indice ...

Having trouble locating the module for my custom TypeScript module

Exciting news! I have recently released a new TypeScript-based module on the NPM registry, called ooafs. However, when attempting to install and import it into another TypeScript project, an error pops up in VSCode stating: Cannot find module 'ooafs&a ...

Can data be transferred between browsers, such as from Google Chrome to Mozilla Firefox?

I have a dilemma with two separate pages—one for Admin and the other for User. The Admin page is named index.html <!DOCTYPE html> <html lang="en"> <head> <style> * { padding: 0; ...

How should filtering be properly done on a data array within a Redux reducer function?

I am trying to develop a function that filters an array based on a search input. The goal is for the filter action to trigger when there's a change in the SEARCH_TEXT. However, I'm facing confusion when it comes to handling the state when the del ...

Guide to utilizing JavaScript for a basic gaming experience

Looking to incorporate multiple divs that will vanish upon being clicked, while also increasing the score by 1 through javascript. Any suggestions on how to accomplish this? ...

Tips for efficiently handling state across various forms in separate components using only one save button within a React-Redux application

I am currently developing an application that combines a .NET Core backend with a React frontend, using React Hook Form for managing forms. Unlike typical single-page applications, my frontend is not built in such a way. On a specific page of the applicat ...

Sharing data between the main component and the sidebar in React-Router

Currently working with Meteor in combination with React-Router, and this is the code I'm dealing with: Routes.jsx: Meteor.startup(() => { render( <Router history={browserHistory}> <Route path='/' component={App}> ...

Tips for adjusting the header color in materialize framework?

I've been working on a web template and I'm looking to customize the color displayed in the Android browser (maybe using JS?). The default color is blue. How can I go about changing it? Appreciate any help! ...

I am looking to obtain assistance through denomongo for guidance

The deno-mongo guide page on GitHub is no longer functional. You can find the page here: 'https://github.com/manyuanrong/deno_mongo' I am struggling to understand how to use the plugin and get it up and running. Following the example in the "Re ...

Simple way to retrieve the first and last date of the current month using Node.js

I need help with retrieving the first and last date of the current month using the code below:- let currentDate = new Date(); let month = currentDate.getMonth() + 1; console.log(month); let firstDate = new Date(currentDate.getFullYear(), currentDate.getMon ...

Is there a way to retrieve the password of the currently logged in user using Keycloak in JavaScript?

Does anyone know how to access the password of a logged-in user in a React application using Keycloak? I have successfully retrieved most of the necessary information from the idToken, like this: keycloak.init({ onLoad: 'login-required'}).then(fu ...

Removing numerous items with checkboxes

Currently, I am working on enhancing my shopping list functionality. I have successfully implemented a feature to delete individual items from the list. However, I am facing difficulty in deleting multiple items using checkboxes. The structure of my item t ...

Retaining the Chosen Tab upon Page Reload in Bootstrap 5.1

Struggling to maintain the selected tab active after page refresh. It's worth noting that I'm using Bootstrap 5.1 and have tried various solutions found for different versions without success. <ul class="nav nav-pills mb-3" id=&q ...

Tips for loading JSP on a Lightbox using jQuery

Looking to showcase JSP Pages in LightBoxes. Would appreciate recommendations on the optimal jQuery API for this task! Appreciate any help, thank you! ...

Async pipe in Angular does not work with my custom observables

I've been trying to implement the async pipe in my template, but I'm encountering difficulties retrieving data from my API. To store and retrieve the data, I have utilized a behavior subject to create an observable. However, when I attempt to dis ...

The code functions properly when run locally, however, it encounters issues when deployed

When testing the following lambda code locally using Alex-app-server, everything works perfectly fine. However, when I publish it and test on AWS Lambda, it gets stuck within the else statement. It prints the console log 'OUT PUBLISH' but doesn&a ...