Muirik
Muirik

Reputation: 6289

Capturing Click Event to Pass Into Function in Angular App

I have set up some filters a user can click on in order to filter a list display in my Angular app. The relevant code in my view looks like this:

<md-checkbox *ngFor="let option of categoryFilters.options" [(ngModel)]="option.value" (click)="filterByCategory($event)">
     {{option.label}}
</md-checkbox>

You'll notice that I have a "filterByCategory()" function above. What I want to do with that is filter the list according to the value that the user clicks on from the md-checkbox list. So far I haven't been able to capture that value.

I've tried this in my component:

public filterByCategory(option) {
    console.log('Category filter ' + option + ' was clicked');
}

But that just prints the mouse event to the console:

'Category filter [object MouseEvent] was clicked'

I also tried using the two-way-bound value, like this:

public filterByCategory(option) {
    console.log('Category filter ' + this.option.value + ' was clicked');
}

But that returns 'undefined'.

By the way, the options I'm trying access the values of here look like this in my component:

private categoryFilters = {
    enabled: true,
    options: [
        { toolbarLabel: 'A', label: 'Option A', value: false },
        { toolbarLabel: 'B', label: 'Option B', value: false },
        { toolbarLabel: 'C ', label: 'Option C ', value: false }
    ],
    text: null
};

What can use to actually get the value that was clicked on, in order to pass that into the filter function?

Upvotes: 1

Views: 923

Answers (2)

AVJT82
AVJT82

Reputation: 73357

UPDATE:

You can also try this:

<md-checkbox *ngFor="let option of categoryFilters.options" 
     [(ngModel)]="option.value" (change)="filterByCategory(option.label, $event)">
   {{option.label}}
</md-checkbox>

filterByCategory(value, checked) {
  if(checked) {
    console.log(value)
  }
}

Original answer:

You could do it like this: I removed the two-way-binding altogether, since we are using $event and value-attribute, so in this case ngModel is redundant. I also use change-event instead of click. So change your template to:

<md-checkbox *ngFor="let option of categoryFilters.options" 
    value="{{option.label}}" (change)="filterByCategory($event)">
       {{option.label}}
</md-checkbox>

And in the component, let's see if the checkbox is checked before actually looking at the option value.

filterByCategory(event) {
  if(event.checked) {
    console.log(event.source.value)
  }
}

This seems to work fine:

Demo

Upvotes: 1

RemyaJ
RemyaJ

Reputation: 5526

Try this. (click)="optionClicked(option)">

optionClicked(option) {
console.log(option.value)
}

Upvotes: 2

Related Questions