Home > Net >  How to send the change event of mat-checkbox from parent to child in angular?
How to send the change event of mat-checkbox from parent to child in angular?

Time:12-01

I made a custom filter (shared) component based on mat-checkbox.

<ul>
  <li *ngFor="let value of values">
    <mat-checkbox [(ngModel)]="value.active" (ngModelChange)="emitState()">
      {{value.title}}
    </mat-checkbox>
  </li>
</ul>

---

import { Component, forwardRef } from '@angular/core';
import { FilterState } from '../filter-state.model';
import { FilterComponent } from '../filter.component';

@Component({
  selector: 'my-checkbox-filter',
  templateUrl: './checkbox-filter.html',
  styleUrls: ['./checkbox-filter.scss'],
  providers: [
    {
      provide: FilterComponent,
      useExisting: forwardRef(() => CheckboxFilterComponent),
    },
  ],
})
export class CheckboxFilterComponent extends FilterComponent {
  constructor() {
    super();
  }

  getState(): FilterState {
    return {
      name: this.name,
      value: this.values
        .filter((value) => value.active)
        .map((value) => value.value),
    };
  }
}

my-checkbox-filter is used in the another component, app/page/search-page/:

// simplified example
<my-checkbox-filter name="checkbox" [values]="checkBoxValues"></my-checkbox-filter>

---

import { myCheckboxFilter } from '../../shared/my-checkbox-filter';
checkBoxValues = [
  {
    value: 'yesterday',
    title: `Yesterday`,
    active: false,
  },
  {
    value: 'tomorrow',
    title: `Tomorrow`,
    active: false,
  }
]

...

// here I would like to detect the filter change
// isChange(event) {
//   console.log("filter is changed")
// } 

The question is I would like to use mat-checkbox's (change) in the my-checkbox-filter. How do I make this connection work, or how to pass change event from search-page to my-checkbox-filter ?

Thank you!

CodePudding user response:

first add $event to your ngModelChange handler to be (ngModelChange)="emitState($event)" then use @output in my-checkbox-filter and in emitState function emit the output eevnt like

@Output()
filterCheckBoxValueChanged= new EventEmitter<boolean>();
.
.
.
emitState(checked: boolean){
  this.filterCheckBoxValueChanged.emit(checked)
}

then bind the returned value in parent class create attribute "isFilterCheckBoxChecked" to bind it with the filterCheckBoxValueChanged in HTML like

<my-checkbox-filter name="checkbox" [values]="checkBoxValues" (filterCheckBoxValueChanged)="isFilterCheckBoxChecked"></my-checkbox-filter>
  • Related