Home > database >  Call an event in Angular Element from custom Element using ID Angular
Call an event in Angular Element from custom Element using ID Angular

Time:03-01

I have been stuck at one place where I am trying to call the Custom element event into the angular element using id

for example:

angularElement.html

<custome-element id="elementId"></custome-element>

AngularElement.Ts

import {
  Component,
} from '@angular/core';

@Component({
  selector: 'angular-element',
  templateUrl: './angular-element.component.html',
  styleUrls: ['./angular-elementcomponent.scss'],
})
export class AngularElementComponent implements OnInit {
  
  callThisFunction() {
    const data: any =  document.getElementById('elementId') as 
     HTMLElement
     data.someFunction(); // not working
    console.log('call function in to custom element');
    alert('test');
  }
}

CustomeElement.Ts

import {
  Component,
  Input,
  OnInit,
  EventEmitter
} from '@angular/core';

@Component({
  selector: 'custome-element',
  templateUrl: './custome-element.component.html',
  styleUrls: ['./custome-elementcomponent.scss'],
})
export class CustomeElementComponent implements OnInit {
  constructor() {}

  ngOnInit(): void {
  }

  someFunction() {
    console.log('call function in to angular element');
    alert('test');
  }
}

Here I want to call the function someFunction() in the Angular element using ID, I know I can call with @output but I need to use ID and call function using the ID.

Here is what i am trying by passing id

const data: any = document.getElementById('elementId') as HTMLElement

data.someFunction(); // not working

CodePudding user response:

the correct syntax is @Output() and not @outPut()

CodePudding user response:

You need to declare an output in child component

@outPut() callParentFunctionName = new EventEmitter<void>();

and then emit it

someFunction() {
    this.callParentFunctionName.emit();
    alert('test');
}

And then in parent component

<custome-element [passdata]="true" (receiveData)="addData()" (callParentFunctionName)="callThisFunctionOnCustomElement()"></custome-element>

Or if You want to call child component function in parent component https://angular.io/guide/component-interaction#parent-calls-an-viewchild

Or by using dispatch event

callTheCardBtn() {
        const data: any = document.getElementById('recaptchaId');
        const event = new CustomEvent("addCard", { detail: { name: "Custom Event Triggered" } });
        data.dispatchEvent(event);

        alert('click me');
    }
  • Related