Home > Software design >  How to access an Angular2 component's methods from another component?
How to access an Angular2 component's methods from another component?

Time:12-20

I am working on an NgForm that is supposed to have a "Reset all fields"-button. I can access NgForm.reset() to reset most of the fields. But I have a couple of instances of a custom multiselect component that is excluded from the reset-method.

The custom multiselect is basically just an <angular2-multiselect> with some <items> attached to it, and it has an "X" button that will clear it's value(s) which works fine. This happens through (onDeSelectAll)="onDeSelectAll($event) on the <angular2-multiselect>.

I am trying to fire this method from another button inside the same NgForm. But I can't seem to understand how to do so. I've tried to make my own method too

<multiselect name="myMultiselect"/>
   // Lots of options

<button (click)="myMultiselect.onDeSelectAll($event)"/>
   // or
<button (click)="ResetMultiSelect($event)"/>

I've also tried to make my own code that does the same thing. This is how I try to do it in typescript:

public myMultiselect : MultiSelect;

function ResetMultiSelect(items: any)
{
   myMultiselect.selectedItems = items;
   // or
   this.myForm.myMultiselect.selectedItems = items;
}

I've tried to set myMultiselect.selectedItems to null, undefined, and [] (empty array). Out of the three only [] seems to work. But when I look in the inspector it tells me that this.selectedItems.split is not a function. So although I get the result I want this way, I get it wrong way.

So my question is basically either

A: Is there a way for me to set selectedItems of my multiselect to be something that clears all options from a function that is triggered by the button?

or B: Is there a good way for my button to find and call my multiselectComponent's onDeSelectAll() method?

CodePudding user response:

Use angular template variables to get a reference of your angular component. Then you could easily call the public method you like on your child component like:

<multiselect #myMultiselect></multiselect>
<button (onClick)="myMultiselect.onDeSelectAll($event)">Click Here</button>

You could also use @ViewChild decorator in your component .ts to retrieve the component you want by its given template variable.

  • Related