简体   繁体   中英

How to access an Angular2 component's methods from another component?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM