Mujtaba Kably
Mujtaba Kably

Reputation: 755

Dynamically attach events to an Input

I am creating a form generator in ng5. Basically, I send it JSON and it generates the form.

I need a way to attach events dynamically to a FormControl. I am passing it the following JSON in:

{
  events: {
     click: 'functionNameHere',
     dblclick: 'functionNameHere',
     so on ....
  }
}

How do I attach any events passed here to my control?

Upvotes: 5

Views: 4603

Answers (2)

elvis_ferns
elvis_ferns

Reputation: 524

In ng5 the best way to attach listeners dynamically would be through the way of Renderer2.

let simple = this.renderer.listen(yourElement, yourEvent, 
(evt) => {
  console.log(evt);
});

You can refer to the answer given by Eric Martinez dynamically adding listeners in angular

Best way would be to create a directive for your form elements like [handleEventInputs] and pass the events data to it.

Use the renderer to listen to the events of only those elements using ElementRef.

Create an event emitter in your directive to send the event data along with the type of event back to your form generator component.

Your component:

<input type="text" [handleEventInputs]="events" (eventData)="myFunction($event)"/>

Your directive:

@Input('handleEventInputs') eventObject = {};
@Output() eventData = new EventEmitter<{type: string, event: Event}>();

this.renderer.listen(this.element.nativeElement, 'your-event', (event) => {
  this.eventData.emit({type: 'your-event', event});
});

Upvotes: 2

axl-code
axl-code

Reputation: 2274

In Angular events are binded to HTML elements. FormControl tracks the value and validation status of an individual form control FormControl official docs.

If you want to define events like click on an HTML element you should do it in this way:

<input (click)="myFuncForClick()" ... />

In order to configure an HTML element programatically (e.g. using a json, an object or whatever) you need to do something more tricky like create a dynamic component but I'm not sure if it's worthy.

Upvotes: 0

Related Questions