Reputation: 4133
I have a child component which generates a couple of input fields dynamically in a parent component.
<app-xxx *ngFor="let el of fieldsElements"
[ngModel]="fieldsElements[el.name]"
...
...
(keydown)="myFunction(yyy, zzz)">
</app-xxx>
The issue is that I would like to call myFunction()
using click()
eventHandler if the input has a specific name, but for the rest, I want to keep (keydown)
. Or let's say for one of the generated input fields, I want to assign (click)
instead of (keydown)
. Example:
<app-xxx *ngFor="let el of fieldsElements"
[ngModel]="fieldsElements[el.name]"
...
...
(click)="myFunction(yyy, zzz)">
</app-xxx>
How can I achieve this dynamically in the HTML/View? I have been trying couple of options using *ngIf
and some other options within the ts
file using an if-statement and addEventListener()
etc.
None of them did help.
Any hint or idea?
Upvotes: 0
Views: 88
Reputation: 57939
I think the most efficient will be use a variable and use the way 'variable && function'. Only if variable is true the function is executed
<app-xxx *ngFor="let el of fieldsElements"
[ngModel]="fieldsElements[el.name]"
...
...
(click)="el.allowClick && myFunction(yyy, zzz)">
(keydown)="el.allowKeydown && myFunction(yyy, zzz)">
</app-xxx>
Update so, e.g. if your fieldsElements are an array of elements, like
fieldsElements=[
{name:"name1",allowClick:true},
{name:"name2",allowKeyDown:true},
{name:"name3"}]
"name1" execute function when (click), "name2" when (keyDown) and "name3" not execute anything
Upvotes: 1
Reputation: 4888
You could use *ngIf (and/or if/else).
<div *ngFor=(etc. etc)>
<div *ngIf="name === 'somename'" (click)="myFunction()">
etc...
<div>
<div *ngIf="name !== 'somename'" (keydown)="myFunction()">
etc...
</div>
</div>
So you're not really dynamically switching handlers, you're just writing out the element you want based on the name you're looking for. But the result is the same.
Upvotes: 0