0

I have two components in angular8. 1) add-files component 2) Discussion Component.

In the discussion component, I am having one button (see below)

<app-add-files></app-add-files>

<div class="col-12 col-sm-6 col-lg-6">
            <input type="submit" value="Send" (click)="removeitems()" class="greenBtn float-right addCommentsBtn"
              [disabled]="commentForm.pristine || commentForm.invalid" onclick="closeCommnetPopupBox()">
          </div>

I want to call a function removedoc() that is defined in the add-files component whenever I clicked on the button that is defined in the discussion component.

I tried with the below approach.

I import the add-files component in the discussion component and created an object of the same and then calling the function from the discussion component to the add-files component.

removeitems()
{
 this.comp.removedoc();
}

comp is the object created of the add-files component.

I was doing some research on the internet and found that we can achieve this with @input/@output decorators with event emitters.

I am new to Angular. can anyone suggest me this approach to how to trigger the function form different components using event emitters with @input/@output in Angular?

Thanks in Advance!

Jayesh Vyas
  • 1,145
  • 3
  • 15
  • 35

1 Answers1

0

You can call the child component class using ViewChild decorator.


// Inside parent component.
@ViewChild('mychild') childComponent: Component2;
  onButtonClick() {

   // Exceute the function of child class.
   console.log( this.childComponent.method1());
  }

// On parent component html.
<component2 #mychild></component2>

You can play with it here.

Shadab Faiz
  • 2,380
  • 1
  • 18
  • 28