mercredi 19 septembre 2018

Angular - how to retrieve inputs as observable in another component?

I'm having troubles finding a clean way to do this, I have a number of checkboxes, and when they are checked or unchecked, something in the view should change. I'm trying to have an observable emitting if the checkboxes are checked or not to other components, so I change the view.

First of all I made a service where I'll keep my observable:

private checkboxesSelectedSubject: new BehaviorSubject<checkboxesSelected>(undefined);

 getCheckboxesSelectedObservable(): Observable<checkboxesSelected> {
    return this.checkboxesSelectedSubject.asObservable();
  }

setCheckboxesSelection(checkboxes: checkboxesSelected): void {
    this.checkboxesSelectedSubject.next(checkboxes);
  }

and I defined this class:

export class checkboxesSelected{
  checkbox1: boolean;
  checkbox2: boolean;
  checkbox3: boolean;
  checkbox4: boolean;
}

so now what I want, is to use this service in the component where I have the checkboxes, so I can update them on change, and from others components, subscribe to this observable to listen for changes.

In the checkboxes components, I have a <mat-checkbox> that has the [(ngModel)]="checkbox.isActive"

and the 4 checkboxes are generated with a *ngFor:

*ngFor="let checkbox of checkboxes; let i = index"

and checkboxes is an array of 4 objects with some properties, and one of them is isActive which gets changed with the checkbox selection.

What's the best way to send the changes to my service?

I was thinking to call the service function setCheckboxesSelection and send over the booleans,

so in the component where I have the checkboxes, I do this:

areCheckboxesActive: checkboxesSelected= {
    checkbox1: this.checkboxes[0].isActive,
    checkbox2: this.checkboxes[1].isActive,
    checkbox3: this.checkboxes[2].isActive,
    checkbox4: this.checkboxes[3].isActive
  };

so like this I'm assigning the initial state of each checkbox to this new variable.

Then I call the service in this function:

setCheckboxesSelection(isActive: boolean, index: number): void {
    this.areCheckboxesActive[index] = isActive;
    this.checkboxService.setCheckboxesSelection(this.areCheckboxesActive);
  }

finally I use this function in the (change) on the mat-checkbox:

<mat-checkbox [(ngModel)]="checkbox.isActive" (change)="setCheckboxesSelection($event, i)">

But apparently something is wrong as I get the error message that setCheckboxesSelection is not a function

And besides this error, is my approach efficient? I don't like the part where I make a new variable and assign each of the 4checkboxes boolean to it, doesn't seem good, but not really sure how could I improve this,

Thank you very much




Aucun commentaire:

Enregistrer un commentaire