Dynamic Component Creation and Event Binding via Component API

Hi,


I am currently working on dynamically creating a MultiSelectComponent and attempting to bind an event handler to it using a component API method. However, I'm encountering an error when using the addEventListener method.

Below is a sample code, and I am seeking assistance on how to correctly bind the event using the component API method.

https://stackblitz.com/edit/github-zlzkt9?file=src%2Fapp.component.ts


ngAfterViewInit(): void {
    const ddlContainerDivHTMLElement = document.createElement('div');
    this.ddlContainer!.element.nativeElement.appendChild(ddlContainerDiv);

    const ddlInstance = new MultiSelectComponent(
      this.ngEle,
      this.sRenderer,
      this.viewContainerRef,
      this.injector,
      this.cdr
    );

    ddlInstance.width = '200px';
    ddlInstance.mode = 'CheckBox';
    ddlInstance.showSelectAll = true;

    ddlInstance.filterType = 'Contains';
    ddlInstance.dataSource = this.dataSource!;
    ddlInstance.query = this.query!;
    ddlInstance.fields = { text: 'ContactName'value: 'CustomerID' };

    try {
      //Adding an EventListener for 'selectedAll' event thows an error ?
      ddlInstance.addEventListener('selectedAll', (eany=> {
        console.log('On SelectedAll value:'e);
      });
    } catch (error) {
      console.error('An error occurred:'error);
    }

    ddlInstance.registerOnChange((e=> {
      console.log('OnChange value:'e);
    });

    ddlInstance.appendTo(ddlContainerDiv);
  } Regards,
Aruna

1 Reply 1 reply marked as answer

KP Kokila Poovendran Syncfusion Team March 6, 2024 11:48 AM UTC

Hi Aruna,


Thank you for reaching out to us regarding the issue you encountered while dynamically creating a MultiSelectComponent and attempting to bind an event handler to it using the component API method. We understand the importance of resolving this issue promptly to ensure smooth functionality of your application.


We have addressed your concern and prepared a sample to demonstrate how to subscribe to the "selectedAll" event of the dynamically created MultiSelect component. Please find the code snippet below:


    ddlInstance.selectedAll.subscribe((argsISelectAllEventArgs=> {

      // Logic to execute when all items are selected

      console.log('All items are selected');

    });

 


In this modification, we subscribed to the "selectedAll" event of the dynamically created MultiSelect component ddlInstance. When all items are selected, the logic within the subscription function will be executed.

You can find the updated sample here: https://stackblitz.com/edit/angular-maf4nv-wbhlz1?file=src%2Fapp.component.html,src%2Fapp.component.ts




If you have any further concerns or questions, please feel free to let us know. We're here to assist you.


Marked as answer
Loader.
Up arrow icon