I'm wondering if there any way to get instance of a directive on DIV element? There's lots of divs, and I would not like handle a list in component.
<div class="item"
(click)="func($event)"
appBoardResize>
</div>
<div class="item"
(click)="func($event)"
appBoardResize>
</div>
The number of divs is unlimited, and I'd like get appBoardResize instance accordingly to each div in func().
NG version:17^
The simplest way will be to just pass the instance of the div, as a parameter to the function, for this we use exportAs
on the directive and specify it on the template reference variable.
import { Component, Directive } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
@Directive({
selector: '[appBoardResize]',
exportAs: 'appBoardResize',
standalone: true,
})
export class AppBoardResize {
innerProp = 'test';
}
@Component({
selector: 'app-root',
standalone: true,
imports: [AppBoardResize],
template: `
@for(item of items;track $index) {
<div class="item"
#directive="appBoardResize"
(click)="func($event, directive)"
appBoardResize>
some div
</div>
<div class="item"
#directive="appBoardResize"
(click)="func($event, directive)"
appBoardResize>
some div 2
</div>
}
`,
})
export class App {
items = new Array(10);
func(event: Event, directive: AppBoardResize) {
console.log(event, directive);
}
}
bootstrapApplication(App);
Another way is to use the viewChildren
function of angular to fetch all the directives in the component, the array, will be available only on the ngAfterViewInit
hook.
Since you are using angular 17 I am recommending the signals way, but the same thing can be done with @ViewChildren(AppBoardResize) directives!: QueryList<AppBoardResize>;
import { Component, Directive, viewChildren } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
@Directive({
selector: '[appBoardResize]',
standalone: true,
})
export class AppBoardResize {}
@Component({
selector: 'app-root',
standalone: true,
imports: [AppBoardResize],
template: `
@for(item of items;track $index) {
<div class="item"
(click)="func($event)"
appBoardResize>
some div
</div>
<div class="item"
(click)="func($event)"
appBoardResize>
some div 2
</div>
}
`,
})
export class App {
directives = viewChildren(AppBoardResize);
items = new Array(10);
func(event: Event) {
console.log(event);
}
ngAfterViewInit() {
console.log(this.directives());
}
}
bootstrapApplication(App);