How to programmatically trigger a click event in Angular 8

Having trouble triggering a click event for an element reference based on its index in Angular 8. If anyone has a solution, please help me out!

Here is the code snippet from app.component.html:

        
        <div class="st-item" *ngFor="let data of datalist; let i = index">
            <input type="radio" name="st" id="{{data.name}}" />
            <label for="{{data.name}}" #items (click)="showproduct(data.name)">
                <span>
                    {{data.display}}
                </span>
            </label>
        </div>

And here is the relevant part of app.component.ts:

  
  @ViewChildren('items') liItems: QueryList<ElementRef>

  ngOnInit(){ 
    const indexItem = 2; 
    this.liItems.forEach((item, index) => {
      if (index === (indexItem - 1)) (item.nativeElement as HTMLElement).click();
    }); 
  }

You can also check out what the liItems object contains by logging it: console.log(this.liItems);https://i.sstatic.net/N6jKv.png

Answer №1

If no errors appeared in the console, it's hard to pinpoint what went wrong. However, two potential issues stand out:

  • ngOnInit may be executed before the view finishes rendering. To ensure that ngFor and the entire view are ready, consider using ngAfterViewInit or ngAfterContentInit. If you're checking this.liItems in ngOnInit and it isn't returning undefined, that would be unexpected.
  • If you encounter an
    ExpressionChangedAfterItHasBeenCheckedError
    , wrapping your code in a setTimeout function might resolve the issue.

Please keep me posted on any new errors or if you need further assistance. Wishing you the best of luck!

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

Angular: Incorporating a custom validation function into the controller - Techniques for accessing the 'this' keyword

I'm currently working on implementing a custom validator for a form in Angular. I've encountered an issue where I am unable to access the controller's this within the validator function. This is the validator function that's causing tr ...

How can I iterate over nested objects using ngFor in Angular HTML?

We have a data object stored on our server structured like this; { "NFL": { "link": "https://www.nfl.com/", "ticketPrice": 75 }, "MLB": { "link": "https:// ...

Master the art of iterating through an Object in TypeScript

I need help with looping through an Object in TypeScript. While the following examples work in JavaScript, I understand why they pose a problem in TypeScript. Unfortunately, I am struggling to find the correct approach to solve this issue. Am I approaching ...

Inaccurate recommendations for type safety in function overloading

The TypeScript compiler is not providing accurate suggestions for the config parameter when calling the fooBar function with the 'view_product' type. Although it correctly identifies errors when an incorrect key is provided, it does not enforce t ...

The parameter does not accept a string as an argument, it only allows for values of "one", "two", "three", "four", "five", or "six"

I'm facing a challenge with my specific type: type OtpCode = { one: string; two: string; three: string; four: string; five: string; six: string; }; I want to iterate through this object and assign values: Object.keys(defaultValues).forEac ...

The 'subscribe' property is not available on the type '() => Observable<any>'

File for providing service: import { Observable } from 'rxjs/Rx'; import { Http, Response} from '@angular/http'; import { Injectable } from '@angular/core'; import 'rxjs/add/operator/Map'; @Injectable() export clas ...

How can you generate a distinct id value for each element within an ngFor iteration in Angular 4?

I encountered an issue where I must assign a distinct id value to each data row within my *ngFor loop in angular 4. Here is the code snippet: <div *ngFor="let row of myDataList"> <div id="thisNeedsToBeUnique">{{ row.myValue }}</div> & ...

Running a TypeScript file on Heroku Scheduler - A step-by-step guide

I have set up a TypeScript server on Heroku and am attempting to schedule a recurring job to run hourly. The application itself functions smoothly and serves all the necessary data, but I encounter failures when trying to execute a job using "Heroku Schedu ...

What is the best way to implement multiple pipe filters in Angular?

I am looking to filter a list of objects based on certain criteria such as status, activity, position, and category. To achieve this, I have decided to create separate pipes for each criteria: StatusPipe, ActivityPipe, PositionPipe, and CategoryPipe. I a ...

Struggling to utilize a custom react-three-fiber component despite specifying the custom type within the react-three-fiber module

Currently developing a react application focused on visualizing mathematical concepts with the help of react-three-fiber. Utilizing TypeScript, I discovered that by extending custom ThreeElements (https://docs.pmnd.rs/react-three-fiber/tutorials/typescript ...

Dealing with string type mismatches in JavaScript when using Typescript

Currently, I am coding in JavaScript with the help of a jsconfig.json file to enhance TypeScript type checking. Unfortunately, it appears that the TypeScript language server is not as advanced as needed to handle these specific situations. The error messa ...

Is there a way to switch an element across various pages within Ionic 3?

Is it possible to exchange information between two pages using logic? I have successfully implemented a checklist, but I am unsure how to add a success/error icon next to the Room name on the 'verifyplace.html' page after invoking the goToNextPa ...

Is it necessary to compile the ngfactory files during Angular 2 AOT compilation?

I've noticed an interesting behavior when compiling my Angular 2 application with `ngc`. During the first run, it generates the `.ngfactory.ts` files for each component but only compiles the TypeScript to JavaScript for other files. This results in no ...

Exploring the integration of React.Components with apollo-client and TypeScript

I am in the process of creating a basic React component using apollo-client alongside TypeScript. This particular component is responsible for fetching a list of articles and displaying them. Here's the code: import * as React from 'react' ...

Can you point me in the direction of the Monaco editor autocomplete feature?

While developing PromQL language support for monaco-editor, I discovered that the languages definitions can be found in this repository: https://github.com/microsoft/monaco-languages However, I am struggling to locate where the autocompletion definitions ...

There is no component factory available for the DialogDataExampleDialog. Have you ensured to include it in the @NgModule entryComponents?

Currently, I am a beginner in Angular. I recently started integrating MatDialog into my project. To do this, I followed the code provided on the official Angular documentation page https://material.angular.io/components/dialog/overview. However, upon click ...

When a child is added to a pixi.js sprite, it causes the child's size and position to become

Using typescript and pixi.js v4.8.2, I have implemented the following code to create containers: let appWidth = app.renderer.view.width let appHeight = app.renderer.view.height mapContainer = new PIXI.Sprite(PIXI.loader.resources.water_pattern ...

What is the easiest way to retrieve a basic date with the month represented by a numerical

Struggling to retrieve the date in the format "Oct 29". I attempted using split but it varies every day. This is what I've come up with so far. let currentDate = new Date().toLocaleDateString('en-US', { month: 'short', day: 'n ...

Join a subscription and remain subscribed in sequential order

Within the code below, there is a nested subscribe function. It takes a schedule_id and retrieves questions based on that schedule_id. The functionality works correctly, but the order in which getQuestion() is executed is not guaranteed. Schedule IDs: 111, ...

Guide on encoding base64 within an Azure DevOps Pipelines extension

I'm in the process of creating an Azure Pipelines extension using Typescript and referring to Microsoft's documentation During my development, I encountered an issue when trying to base64 encode a string using the btoa() function which resulted ...