Majid Majed
Majid Majed

Reputation: 338

Is it possible passing directive to the event handler in angular?

Is it OK in angular to do this:

//template file
<input *ngFor="let elem in elements" [myDirective]="elem" 
      (keyup.enter)="onEnter(myDirective)">

//.ts file
onEnter(dir: MyDirective){
   //access myDirective instanse here
}

I know I can do this by @ViewChildren but I want to ensure is it OK to pass directly?

Upvotes: 0

Views: 37

Answers (1)

user184994
user184994

Reputation: 18281

In your directive, make sure you set exportAs:

@Directive({
 selector: '[myDirective]',
 exportAs: 'myDirective'
})

Then, you can get a reference to it in the template:

<input *ngFor="let elem in elements" [myDirective]="elem" #test="myDirective"
  (keyup.enter)="onEnter(test)">

Here I've called it test, but you can call it whatever you want

Upvotes: 2

Related Questions