dimanche 9 septembre 2018

I can't implement a select all checkbox and normal checkbox as two separate components in Angular 6

I am trying to create two components in Angular 6: a "checkbox" component, acting as a normal checkbox, and a "select all checkbox" component, that checks/unchecks all the checkbox components.

To make this work, I use a service with a method that emits a boolean value on a Subject:

areAllCheckedSource = new Subject<boolean>();

selectAllSingle(checked: boolean) {
    this.areAllCheckedSource.next(checked);
}

selectAllSingle() is then called in another method in the "select all checkbox" component, with an internal boolean value as the argument:

multiCheckStatus: boolean;

constructor (private checkService: SelectAllService ) {
}

checkAll() {
  this.multiCheckStatus = !this.multiCheckStatus;
  this.checkService.selectAllSingle(this.multiCheckStatus);
} 

the checkAll() method is binded to the (change) property of the HTML checkbox element, used in the template:

<input type="checkbox" [checked]="multiCheckStatus" (change)="checkAll()">

Finally, the "checkbox" component subscribe to the subject, to set his internal boolean according to the emitted value:

singleCheck: boolean;

  constructor(private multiCheckParent: SelectAllService) {
  }

  ngOnInit() {
    this.multiCheckParent.areAllCheckedSource.subscribe( checked => {
      this.singleCheck = checked;
    });
  }

My problem is that the checkbox component doesn't change to match the select all component; I noticed that if I use a BehaviorSubject instead of a regular Subject, the initial boolean passed as argument is received, but subsequent values are not.

Also here is a working example of the code: https://stackblitz.com/edit/angular-ecwlua?file=components%2Fselectall%2Fselectall.component.html

I'm fairly new to Angular development, and I don't understand if this is a problem with the way I use the subscribe or with the general implementation. Can anyone help me? Thanks.




Aucun commentaire:

Enregistrer un commentaire