How to access elements by their class name in Angular

Recently, I encountered a situation with this specific span element:

<span *ngFor="let list of lists[0].question; let i = index" id="word{{ i }}" (click)="changestyle($event)" class="highlight">
  {{ list}}
</span>

While attempting to retrieve all elements with the highlight class,

check() {
    let highlight_text= $('.highlight');
    console.log(highlight_text.length);
    for (let i = 0; i < highlight_text.length; i++) {

I am perplexed by the fact that it returns a length of 0 despite having elements with this class. It should be returning those elements.

If you have any solutions or suggestions, please share. Thank you!

Answer №1

The issue revolves around the invocation of the check function, which is not ideal within the ngOnInit. I attempted to address this by utilizing the ngAfterViewInit method like so:

ngAfterViewInit(): void {
    this.check();
  }

Upon implementation, I observed that the length is greater than zero.

Answer №2

Responding to @The Fabio's comment beneath his answer and offering a potential solution to the initial question.

What are the drawbacks of using functions to evaluate classes in [ngClass]? Or more broadly, why is it discouraged to incorporate function calls in Angular template expressions?

The issue arises from Angular's change detection mechanism needing to invoke the function to check for changes => when iterating through extensive lists, the function will be called numerous times even if there is no relevant alteration. This means the function gets executed whenever you interact with buttons, input fields bound to it, and so forth. Refer to the Stackblitz Demo.

To tackle this problem effectively, examining the original list and considering alternative approaches is key. I recommend utilizing the View Model, which extends properties of the original Data Model.

// Proposed Question View Model
// extending the original one allows adding new properties while retaining the old ones
interface IQuestionVM extends IQuestionDTO { 
  hasHighlight: boolean
}

//somewhere in the code, ngOnInit is a suitable place for this
this.processedQuestions: Array<IQuestionVM> = this.lists[0]question.map(q => ({
 ...q, // spread the original object
 hasHighlight: q.something === 0 // evaluate the condition and assign to extended property
}))

This approach simplifies and optimizes the HTML template:

<span 
  *ngFor="let list of processedQuestions; let i = index" id="word{{ i }}"
  (click)="changestyle($event)"
  [ngClass]="{ 'highlight': list.hasHighlight }"  
>
  {{ list }}
</span>

This method removes the necessity for a dedicated function to assess the class, eliminates the need to search for elements manually, and streamlines handling highlight updates. No extra variables, arrays, functions, or jQuery are required anymore.

Answer №3

Combining angular with jQuery can lead to a lot of improvisation...

If you want to set the class of an element based on attributes, your best option is to use the ngClass Directive:

<span *ngFor="let list of lists[0].question; let i = index" id="word{{ i }}" (click)="changestyle($event)" [ngClass] = {'highlight': shouldHighlight(list)}>
  {{ list }}
</span>

In the component, create a function like this:

shouldHighlight(list) {
  // define your condition here, returning true or false
}

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

In Angular with rxjs, make sure the response is set to null if the json file cannot be found during an http.get request

When working on my Angular app, I often retrieve data from a static JSON file like this: @Injectable() export class ConfigService { constructor(private http: HttpClient) { } getData() { this.http.get('/assets/myfile.json').subscribe(da ...

Challenge with validating reactive forms

*ngIf not behaving as expected Although my form's primary condition is working flawlessly, I am facing issues with displaying a specific error message. For example, the code *ngIf="PopupForm.get('startdate').errors?.required is not fun ...

Sharing Information Across Angular Routes

I've been encountering a slight issue when working with routes in Angular 4. Whenever I attempt to pass data from one component to another using navigate('root', data), all I end up receiving is [object Object],[object Object],[object Object ...

Difficulty in dynamically changing Angular 6 directive attributes

I am currently working with component A, which features a custom directive on the web page: Here is how it looks: <warning [details]='details'></warning> The code for Component A is as follows: export class AComponent implemen ...

A different approach to showcasing components in SvelteKit based on the width of the screen

In my SvelteKit app, I'm using this code to retrieve the current window size and switch the displayed component when the width is small: <script> let size; </script> <svelte:window bind:innerwidth{size}/> <div> {#if size &g ...

While deploying: Error 500 - The installation of dependencies was unsuccessful due to a request timeout

I'm encountering an issue while attempting to deploy my bot to Azure. Here's the command I used: az bot publish --name --proj-name "" --resource-group --code-dir "/path/to/my-app" --verbose --version v4 Unfortunately, it is timing out durin ...

Enhance the appearance of a custom checkbox component in Angular

I developed a customized toggle switch for my application and integrated it into various sections. Recently, I decided to rework it as a component. However, I am encountering an issue where the toggle switch button does not update in the view (it remains t ...

Encountering an issue with ng serve following the update of Angular, Material, and Bootstrap

Here is the package.json configuration: angular: 5.2.8 angular material : 5.1.1 angular/cli: "~1.7.3" bootstrap: "~4.0.0" Encountering an error while running ng serve: ERROR in ./node_modules/raw-loader!./node_modules/postcss-loader?? embedded!./nod ...

Issue with setting values in Angular2 when using IE 11 and shims included

First off, I want to clarify that I have indeed added the shims in my index.html file. <script src="node_modules/es6-shim/es6-shim.min.js"></script> <script src="node_modules/systemjs/dist/system-polyfills.js"></script> <script ...

When utilizing JavaScript syntax and performing API testing with Postman

Hello, I need some assistance from experts in connecting to Postman using the JavaScript code provided below. When running nodemon, the connection appears to be normal with no errors. Also, the GET request sent to Postman works fine. However, I am encounte ...

Create type declarations using the Typescript compiler by running the command:

After generating my definition file ".d.ts" using tsc --declaration or setting declaration as true in the tsconfig.json, I noticed that the generated files are missing declare module "mymodule" {... } This appears to be causing issues with "tslint" which ...

Error in Typescript: The identifier 'Proxy' is unknown

I'm trying to create a new variable using the Proxy type from the ES6 specification: myProxy: Proxy; However, I'm encountering the following error: Cannot find name 'Proxy'. Can anyone point me in the right direction to resolve th ...

Unable to populate ng2 piechart with received data from HTTP response

Below is the HTML markup I've used to display a pie chart from the NG2-Chart library, which has a dependency on chart.js: <h2>Home</h2> <div style="display: block"> <canvas baseChart class="chart" [data]="pieChart ...

Unclear on the usage of "this" in arrow functions?

After going through various discussions and articles on this topic, I find myself still perplexed about the meaning of this in arrow functions. I've been encountering run-time errors with a code snippet similar to the following: export class Foo imp ...

Converting HTML to PDF with rtl support using the JavaScript library jsPDF

I'm attempting to convert HTML to PDF using jsPDF in an Angular 5 project. Below is the code I have so far: import * as jsPDF from "jspdf"; . . . htmlToPdf(){ var doc=new jsPDF(); var specialElementHandlers = { '#content' : function ...

How can I implement a method to configure a 404 HTTP header in Angular 5 when a route is not found?

Is it possible to display a custom 404 header on the current page when there is no route matching my array? If not, could this potentially create SEO issues and have unknown pages indexed by search engines? ...

Having trouble with an external JavaScript file in Angular 5?

Recently, I decided to delve into the world of Angular and started my journey with angular5 by following this tutorial. Currently, I am in the process of converting a traditional HTML template into an Angular5 version but have encountered some challenges ...

Differing preferences for indentation styles can lead to conflicting prett

My eslint setup is as follows: { "env": { "es2020": true, "jest": true }, "extends": [ "eslint:recommended", "plugin:react/recommended", "plugin:import/recommended&q ...

Setting up Vue CLI 4 with ESLint, TypeScript, Stylelint for SCSS, and Airbnb rules in the VS Code editor with automatic fixes on save

After struggling with configuring Vue CLI 4 with ESLint, Prettier, Airbnb rules, TypeScript, and Vetur, I found myself at a crossroads. The challenges continued to mount as the nature of the problem evolved from my previous attempts.: How to configure Vue ...

Angular 7 throwing errors of undefined variables

I encountered an error message that says Property 'country' does not exist on type 'ViewComponent'. Did you mean 'country$'? I'm at a loss on how to resolve this issue. I understand that there is an undefined variable ca ...