Utilizing object properties to bind the elementRef selector in Angular for seamless HTML integration

I need to dynamically bind an element reference from an object to my HTML in Angular. I have attempted the following:

<div #[sec_variable] ></div> OR <div #sec_variable ></div>

And then tried to retrieve it using @ViewChild(), but it always returns null.

<div class="nav-item" *ngFor="let input of inputs">
  <div #[input.name] /></div>
</div>

Additionally,

 @ViewChild('image',{static:true,read:ElementRef}) img?

 ngOnInit(): void {

  const label = this.renderer.createElement('label');
  this.renderer.setAttribute(label, 'for', 'image');
  this.renderer.appendChild(this.img.nativeElement, label)
 }

However, these methods are not working for me. Is there a way to use it dynamically?

Answer №1

Something similar to this:

@ViewChild('inputEmail') inputEmail!: ElementRef<HTMLInputElement>; 

also

<input #inputEmail>

Just a heads up, in your scenario, the static attribute is not applicable because the element you are trying to query is dynamically created by the ngFor directive.

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

Parsing errors occurred when using the ngFor template: Parser identified an unexpected token at a specific column

In my Angular CLI-built application, I have a component with a model named globalModel. This model is populated with user inputs from the previous page and displayed to the user in an HTML table on the current page. Here's how it's done: <inp ...

Handling image errors in jQuery for responsive design queries

Images on my website change based on the screen size using media queries. I am looking for a way to handle errors that may occur using jQuery. I want to display a text message if the image fails to load. Here is the code I have so far: <div class="con ...

What is the best way to save objects in the store (ngrx, ngxs) while preserving their methods functionality?

As I delve into the Redux pattern, I realize the importance of storing only plain objects in the Store. However, I find myself wanting to use more complex objects with methods like "hasParent", "isReadonly", and "isValid" in my application. While ngrx all ...

The post request is successful in Postman and cURL, however, it faces issues when executed in Angular

A remote server and a local client are set up to communicate through a simple post request. The client sends the request with one header Content-Type: application/json and includes the body '{"text": "hello"}'. Below is the s ...

Use the CLI to install both the alpha and beta versions of Angular on your system

I'm interested in switching to a version of angular that is currently in active development and testing, like 8.0.0-beta, however I currently have 8.1.0 installed. What is the best way for me to downgrade from version 8.1.0 to 8.0.0-beta? ...

Choosing the open status of an HTML list

Is there a way to determine which containers in a list are currently open and which ones are still closed? Currently, I am utilizing the slideDown(), slideDown(), and addClass functions on divs with the specific class="section_hdl_aktiv". However, I want ...

"Using a function parameter as a key in a JSON object

While I may not be a JSON expert, I am struggling to understand why this code is not functioning as expected and what steps I need to take to fix it. Despite my efforts to search for solutions, I suspect that my lack of familiarity with the correct termino ...

What are the best ways to utilize @types/bootbox and @types/jquery?

Is there a way to incorporate @types/bootbox and @types/jquery into an Angular 4 project? I attempted the following: npm install @types/bootbox and in my code, I am implementing it like so: import * as bootbox from 'bootbox'. However, I encou ...

billboard.js: The 'axis.x.type' property is conflicting with different data types in this context

axis: { x: { type: "category" } }, An issue has arisen: The different types of 'axis.x.type' are not compatible with each other. The value of 'string' cannot be assigned to '"category" | &qu ...

Tips on incorporating the authorization header in the $.post() method with Javascript

When attempting to POST data to the server, I need to include an Authorization header. I attempted to achieve this using: $.ajax({ url : <ServiceURL>, data : JSON.stringify(JSonData), type : 'POST', contentType : "text/html", ...

An asynchronous function will never conclude its execution

Exploring the native async and await features in Node 7.6.0 has left me puzzled. I can't seem to figure out why my async call is just hanging instead of resolving. NLP module: const rest = require('unirest') const Redis = require('io ...

Creating an interactive form in Angular2 using *ngFor, implementing two-way data binding with [(ngModel)], and including form validation

Challenge Description I'm currently working on developing a dynamic form that can update parts of the interface based on changes in the underlying model: When a user clicks a button, a new entity is added to the internal list of components and a ne ...

What is the process for estimating based on the departure time and arrival time from previous and subsequent trips?

https://i.stack.imgur.com/pHSkx.png I'm currently faced with a challenge involving a list of arrival and departure timings. Let's say in the image provided, when i = 3 and i = 4 have a departure time of 0. What I aim to accomplish is to utilize ...

Expanding upon the Ember.js Model's save functionality

I have incorporated promise-based code (MyLib) that needs to execute on every model save by extending the save function: DS.Model.extend save: -> parentSave = @_super.bind this, arguments... deferred = Ember.RSVP.defer() MyLib.func().t ...

Tips for identifying and logging out a dormant user from the server side using Angular 2 Meteor

I'm currently diving into Angular 2 Meteor and working on a project that requires logging out the user when they close their browser window. I also need them to be redirected to the login page when they reopen the app. After searching online, I could ...

The global cli npm package functions properly on Windows operating systems, but encounters errors on Linux

I am interested in developing an npm CLI tool. After examining bower's code, I decided to replicate their basic package.json structure along with the bin and lib/bin file. Everything works perfectly on Windows, but when I try to run it on Linux, I en ...

The MongoDB bitwise operation does not return any results when checking for a

I am trying to perform a bitwise check on my data without returning any data. The default value for Rights parameter is 1. How can I resolve this issue? db.getCollection('forms').find( { "IsActive" : true, "$or" : [ { "$where" ...

Passing data through events from a parent component to a child component in Vue.js using the $emit method

Having trouble making this work! I have included the $emit code in my click event to trigger a custom event. <h2 class="form_section--header">Business Hours - <a href="javascript:void(0)" v-on:click="$emit('addBusinessHours', null)"> ...

Encountering unexpected null values post-service invocation in Angular 2

I have encountered an issue in Angular 2 where a variable is returning undefined. The problem arises when a function calls a service to initialize a variable, which is then used in another function to make a get HTTP request. However, the get request fails ...

Extracting data from the Sanity API response in JSON format using Typescript

Struggling with extracting information from a Sanity Client API call and decoding the resulting JSON data. Can someone guide me on how to access specific values? Below is the output of the API call: [ { slug: { current: "test-post", _type: ...