4

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?

0

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This was perfect. The $event I got from doing it this way did not work with onDeSelectAll() so I just made a new method in my typescript that set the selection to an empty array instead with myMultiselect.selectedItems = [] and then updated the view. I then called this method from my button just like in your example.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.