Choosing a single element through viewChild using the "#" selector in Angular 2

Is there a special method to choose multiple tags on the same level with the same tag?

<div #el></div>
<div #el></div>
<div #el></div>

I keep getting an error message that says "Reference "#el" is defined several times."

Appreciate any help in advance!

Answer №1

My approach works well for handling multiple elements with the right selector.

I had a requirement to dynamically load a popup modal from the code base and perform actions like Minimize, Maximize, Close, and Resize. To achieve this, I needed to select one opened modal to carry out operations, and here is how I solved it.

Here is the HTML snippet where I used #dynamicPopupContentPlaceHolder as the selector for the div tag.

https://i.stack.imgur.com/0Pv5d.png

Firstly, I added QueryList in the component from the angular/core library as illustrated below.

https://i.stack.imgur.com/Hq6NS.png

Finally, in the component file, I utilized QueryList (which contains an array of children) to retrieve all the children using the following method.

https://i.stack.imgur.com/D9Wkp.png

Lastly, I used the widgetSelector variable to select the last child from the array using the following technique.

let _targetSelector = this.widgetTargets.last;

Answer №2

Don't forget to add the ViewChildren module.

import {Component, ViewChildren} from 'angular2/core'

You can now implement the code below.

@ViewChildren('el') elements:QueryList<ElementRef>;

Answer №3

Forget that idea, I ended up finding a different method, although it's not as clean

<div #el>
  <div el></div>
  <div el></div>
  <div el></div>
</div>

Instead, for selecting all elements, use querySelectorAll

@ViewChild('el') element: ElementRef;
this.element.nativeElement.querySelectorAll('[el]')

Thank you everyone

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

Guide on implementing Observables in Angular 2+ to update a single entry in a table in real-time

I'm facing a challenge with my Angular4 and Node.js application. I have a table that displays data with 7 columns using *ngFor. The issue arises when I need to update the last column dynamically and in real-time. Specifically, I want to show a green c ...

Is annotation functionality available in version 3 of Chart.js?

In the previous version 2 of the chart, I utilized 'annotation' within options. However, after upgrading to version 3, it seems to have stopped working and I am unable to locate any information about this in the documentation. The following code ...

Ionic app encountering issues with Facebook OAuth login functionality

Currently, I am implementing Facebook Auth for my Ionic app by using the Firebase module. Despite setting up the firebase module correctly initially, I keep encountering an error during the login process. It should be noted that the login function worked p ...

What is preventing me from utilizing a union type in conjunction with redux connect?

Below is a brief example of the code I am working on: import { connect } from "react-redux"; interface ErrorProps { error: true; description: string; } interface NoErrorProps { error: false; } type TestProps = ErrorProps | NoErrorProps; ...

How to extract a specific Observable<T> from an Observable<T[]> array in RxJS

When studying Angular, I created a simulated web service that accomplishes two tasks: It provides an Observable of an array (Observable<T[]>) It offers an item identified by ID as an Observable (Observable<T>) This is the approach I used: e ...

Adding a new line in the configurations of MatDialogConfig (Angular)

Here is a code snippet: private mDialog: MatDialog, const dialog = new MatDialogConfig(); msg = "I enjoy coding in Angular.\r\n I am learning TypeScript." dialog.data = { message:msg }; alert (msg); mDialog.open(AB ...

Resolve the conflict with the upstream dependency when setting up a fresh Angular project

Software Info: Angular CLI: 12.1.1 Node: 14.17.3 Package Manager: npm 7.19.1 An error occurred while attempting to create a new Angular project. npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While re ...

Is there a way to include values in the body of an HTTP GET request using Angular?

I've created a function in my service that looks like this: /** * Retrieve all data * @param sendSelectedValues string */ getAllActPlanBalanceYearData(sendSelectedValues: any): Observable<any> { const url = `/yearlyvalues/act-and ...

What is the method for retrieving interface key types in TypeScript?

My question relates to an interface. interface Some { key1: string key2: number } I am working with a function. const fn = (key: keyof Some) => { return <Some>someObject[key] } Is it possible to determine the return type based on a string ...

Typescript i18next does not meet the requirement of 'string | TemplateStringsArray NextJS'

While attempting to type an array of objects for translation with i18next, I encountered the following error message in the variable navItems when declaring i18next to iterate through the array Type 'NavItemProps[]' does not satisfy the constrain ...

I am currently working on developing a web application for a class assignment and I am unsure whether I should opt for PHP7 Non Thread Safe or Thread Safe version

While I consider myself a beginner in the realm of programming, my knowledge is limited to Python. However, I am eager to explore using PHP7+ and Typescript with Angular 2+. I've come across recommendations for these languages online, but I'm uns ...

Typical approach to receiving a transformed object from an HTTP service

One of the services I provide includes a method with the following implementation: public fetchCrawls(page: number): Observable<ICrawl[]>{ return this._http.get(this._crawlsURL + page) .map((res: Response) => { ...

Changes on services do not affect the Angular component

Currently facing an issue with my Angular assignment where changing an element's value doesn't reflect in the browser, even though the change is logged in the console. The task involves toggling the status of a member from active to inactive and ...

Change the spread operator in JavaScript to TypeScript functions

I'm struggling to convert a piece of code from Javascript to Typescript. The main issue lies in converting the spread operator. function calculateCombinations(first, next, ...rest) { if (rest.length) { next = calculateCombinations(next, ...res ...

Running Protractor tests with 'directConnect: true' causes the ERROR:browser_switcher_service.cc(238)] XXX Init() to be thrown

While running Protractor tests with directConnect: true, I am encountering an error as soon as the browser window appears. Interestingly, the test continues to run smoothly without any apparent issues. However, when I switch to Firefox or use seleniumAddr ...

Display the toggle button for expanding/collapsing text only when the length of the string exceeds 50 characters

Is there a way to only show a "read more/less" button in a table if the content exceeds 50 characters? The table contains a mix of content, some short announcements with about 10 characters and others with over 100. <div class="col"> <span ng-c ...

Angular 2's ng-required directive is used to specify that

I have created a model-driven form in Angular 2, and I need one of the input fields to only show up if a specific checkbox is unchecked. I was able to achieve this using *ngIf directive. Now, my question is how can I make that input field required only whe ...

Issues with Angular's router outlet link functionality not performing as expected

I am encountering difficulties trying to create a link to a named router outlet in Angular. Let's focus on the most crucial part of the code: app-routing-module.ts: import { NgModule } from '@angular/core'; import { RouterModule, Routes } ...

How to open a print preview in a new tab using Angular 4

Currently, I am attempting to implement print functionality in Angular 4. My goal is to have the print preview automatically open in a new tab along with the print popup window. I'm struggling to find a way to pass data from the parent window to the c ...

Issue with selecting a value in React MUI and default value not being defined

Currently, I am working on creating a form in React using MUI and Formik. While implementing the select feature with default values fetched from an API object, I encountered issues where the select function was not working as expected. Strangely, I couldn& ...