0

I want to bind an elementref from an object to my html in angular. What I tried is:

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

and get it from @ViewChild() but it says its null.

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

AND

 @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)
 }

BUT it is not working. How can I use it dynamicaly

  • you can not, you need use ViewChildren and get the QueryList: `@ViewChildren('mydiv') list:QueryList`. But be careful, you can not access in ngOnInit, else in ngAfterViewInit – Eliseo Jun 07 '23 at 08:21

1 Answers1

0

Somenting like

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

and

<input #inputEmail>

And by the way in your case, static is not true since the element you are quering for is being created dynamically by ngFor directive.

Bruno Miguel
  • 1,003
  • 3
  • 13
  • 26
  • u mean #inputEmail in a var driven from an object not a hard code? – reza hrkeng Jun 07 '23 at 07:53
  • I didnt understand sorry. #inputEmail is called a template reference in Angular. And this one of the ways how you can query elements/components from the template (Html) to code behind (TS). Make a search by angular template reference on google, maybe it will help you. – Bruno Miguel Jun 07 '23 at 07:57
  • listen what I am trying to do is: there is no #inputEmail. instead I have an array or object and use ngfor to create
    s with dynamic template ref like this:
    then in ts get them like this: viewchild(fisrt) first; WHICH "first" is the first value in my array: my-object=['first','sec'] For Example
    – reza hrkeng Jun 07 '23 at 08:01
  • like this : https://stackoverflow.com/questions/44440879/dynamic-template-reference-variable-inside-ngfor-angular-9 – reza hrkeng Jun 07 '23 at 08:07
  • 1
    https://stackoverflow.com/questions/53016596/angular-5-access-divs-list-using-viewchildren – Bruno Miguel Jun 07 '23 at 08:08
  • so I did wrong. but your answer in comment above was totally correct and matches with my will. I appreciate you – reza hrkeng Jun 07 '23 at 08:39