54

My template has something like this:

<div *ngFor="let data of array">
    <div #div></div>
</div>

is there a way for me to name each div differently using the #? And if so, how can I access them later in my TS file?

by the way, what are these # called? I cant search for them since I have now idea what these are (I just know what they're used for)

Gustavo Berwanger
  • 684
  • 1
  • 5
  • 9
  • 3
    Pity, but it's impossible to name these references dynamically, so you can't do something like `#div{{i}}`. – P.S. Jul 09 '18 at 19:05
  • 1
    They are called template reference variables - https://angular.io/guide/template-syntax#ref-vars – Wand Maker Jul 09 '18 at 19:06
  • 2
    Can you tell us more about why you need to name them dynamically and what's your final goal? – maxime1992 Jul 09 '18 at 19:12
  • 1
    these divs will be filled with Konva images after an image submit, but I need to get their size whenever I resize my window (which I did using window:resize), create them or do some other stuff like minimizing/maximizing the window, which I beieve can be done through events and having references to them using viewChild – Gustavo Berwanger Jul 09 '18 at 19:25

3 Answers3

72

TL;DR Use ViewChildren instead of ViewChild

As @Commerical Suicide mentioned you cannot set the references dynamically.

The #div is called template reference variable.

You can access your divs via ViewChildren in you *.ts file.

Sample: @ViewChildren('div') divs: QueryList<ElementRef>

Then you can call multiple methods on your new QueryList, like forEach or find.

Abdullah Saleem
  • 3,701
  • 1
  • 19
  • 30
Batajus
  • 5,831
  • 3
  • 25
  • 38
4

There is an alternative way to catch and handle dynamic elements inside the loop by events.

<div *ngFor="let name of names">
  <input #boofoo type="text" (click)="onClick($event, name)" />
  <button (click)="boofoo.click()">Change text</button>
</div>

See example stackblitz

Vassilis Blazos
  • 1,560
  • 1
  • 14
  • 20
2

You can create a child component that will have its logic

Exemple :

menu-horizontal.component.html

<nav id='site-header__nav__desktop'>
    <template-menu-item *ngFor="let link of navLinks" [navItem]="link">
    </template-menu-item>
</nav>

menu-item.component.html

<div>
    <a class="nav-link" #parent routerLink="/test" (click)="toggle()">
        {{ navItem.text }}
    </a>
    <ul #children class="children-menu" *ngIf="navItem.children">
        <li *ngFor="let child of navItem.children">
            <a [href]="child.link">
                {{child.text}}
            </a>
        </li>
    </ul>
</div>

In this example the action of toggle targets the child of the menu item, otherwise it will have selected the first children found

Nullable
  • 761
  • 5
  • 17
charlesb9
  • 21
  • 1