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

Is there a way to declare the different types of var id along with its properties in Typescript?

I recently received a task to convert a JavaScript file to a TypeScript file. One issue I am currently facing is whether or not I should define types for the 'id' with this expression, e.g., id={id}. So far, I have tried: Even though I defined ...

Is there a way to retrieve the value of an option passed by serverless CLI in serverless.ts file?

As I explored the serverless framework with serverless.ts for configuration, a certain question came to mind. When utilizing the serverless CLI, passing values can be done in the following way: serverless offline --stage prod In the serverless.yml file, ...

Ways to customize background color for a particular date?

I have been using the fullcalendar npm package to display a calendar on my website. I am trying to figure out how to set a background color for a specific selected date. I tried looking into this issue on GitHub at this link. However, it seems that dayRe ...

Issues arise in Ionic 3 when attempting to use scripts or external custom jQuery plugins within inner pages

When I utilize a script tag in my index.HTML file, it functions properly on the initial or root pages of Ionic 3. However, upon navigating to other pages using NavController, the script ceases to work on these inner pages. How can I implement a custom jQ ...

Disabling page transition animation in Ionic 4 / Angular: Step-by-step guide

Is there a way to disable the page transition animation when using 'routerLink' to navigate to a new page? I've searched through the documentation and other sources but couldn't find a straightforward answer. Any guidance on this would ...

Learn the steps to dynamically show a navbar component upon logging in without the need to refresh the page using Angular 12

After logging in successfully, I want to display a navbar on my landing page. Currently, the navbar only shows up if I reload the entire page after logging in. There must be a better way to achieve this without a full page reload. app.component.html <a ...

The importation of TypeScript source modules is not compiled accurately in the distribution folder

Currently, I am working on a REST API in TypeScript with the following structure: ├── dist │ ├── index.js │ ├── library.js ├── src │ ├── index.ts │ ├── library.ts ├── node_modules ├── package. ...

When the text in the mat-expansion-panel header exceeds the available space, it will be truncated

Is there a way to add the CSS text-overflow: ellipsis style to a mat-expansion-panel in order to display collapsible text with 3 dots? I have tried implementing it in the mat-expansion-panel-header, but it doesn't seem to work. Here is an image illust ...

Incorporate a module that was developed locally into your project

Attempting to incorporate a locally developed Angular project/module into an angular application without having to publish it on the npm repository has been quite a challenge for me. To begin with, I decided to follow a tutorial that guided me through bui ...

Understanding Mongodb: the process of populating a schema that is referenced within another schema using an API

Looking to make adjustments to my Api in order to populate a referenced schema. Here's the schema I am working with: export const taskSchema = new Schema ({ user:{ type: String, required: true }, project: { type ...

My goal is to create a comprehensive collection of stories showcasing all Material UI components in React

Looking for a way to efficiently import all MUI components stories into my storybook. Is there a tool or repository available that can automate the generation of these stories, or perhaps has pre-written stories for all MUI components? I attempted to cre ...

Unable to locate module, encountered a webpack alias issue while using typescript and react

I'm currently in the process of setting up aliases in webpack. My goal is to make importing components in App.js easier by replacing: ./components/layout/Header/Header with: @components/layout/Header/Header This way, I can avoid potential issues w ...

The length of video files created by MediaRecorder is not retained

This component prompts the user for camera access, displays a video preview, and allows the user to watch it again with video controls such as downloading or navigating to specific moments. However, there is an issue where the recorded video seems to be ...

The ngmodel variable is not responding to dynamic changes

I'm currently working on dynamically changing a date and getting it to reflect in the view, but for some reason it's not showing up. When the date is hard-coded in an array like this, it works perfectly fine and shows up in the view. My date : Ar ...

Encountering an unexpected token error while building an Angular4 --prod project that involves Three

Encountering an error while trying to build an Angular4 project in production with the following command: node --max_old_space_size=8192 'node_modules/@angular/cli/bin/ng' build --prod --output-hashing=al Error: ERROR in vendor.422622daea37e ...

Watching the Event Emitters emitted in Child Components?

How should we approach utilizing or observing parent @Output() event emitters in child components? For instance, in this demo, the child component utilizes the @Output onGreetingChange as shown below: <app-greeting [greeting]="onGreetingChange | a ...

Is time-based revalidation in NextJS factored into Vercel's build execution time?

Currently overseeing the staging environment of a substantial project comprising over 50 dynamic pages. These pages undergo time-based revalidation every 5 minutes on Vercel's complimentary tier. In addition, I am tasked with importing data for numer ...

Exporting numerous modules from an NPM package

Currently, I am working on a large Node and Typescript project called Project A. This project consists of numerous modules that I intend to reuse in another project, Project B. In order to achieve this reusability, I have configured the tsconfig.json file ...

What kind of registration does React Hook Form use?

When utilizing react-hook-form alongside Typescript, there is a component that passes along various props, including register. The confusion arises when defining the type of register within an interface: export interface MyProps { title: string; ... ...

Outside the observable in Angular, there is a vacant array

Within my Angular application, I am facing an issue with the following code snippet located inside a method: let cardArray: string[] = []; this.cardService.getCards().subscribe((cards) => { console.log("1", cards); for (const card of car ...