0

In my html template I'm having multiple elements generated by *ngFor.

I am successfully able to subscribe to their value changes in the ngAfterViewInit lifecycle hook.

However, I am not able to set the .checked property via code.

Does somebody spot my error? Any help is really appreciated!

export class GroupsExpPanelComponent implements AfterViewInit {

  @ViewChildren('confirm') confirm: QueryList < MatButtonToggle > ;
  confirmToggles: MatButtonToggle[] = [];

  ngAfterViewInit() {
    this.confirm.changes
      .subscribe(
        res => {
          this.confirmToggles = res.toArray();
        }
      );
  }


<mat-button-toggle #confirm>Title</mat-button-toggle>

I would have expected to be able to set my properties like so

this.confirmToggles[index].checked = true;
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
baouss
  • 1,312
  • 1
  • 22
  • 52

1 Answers1

0

this.confirmToggles[index] is a reference to a native element, not a native element in and of itself, nor an instance of the MatButtonToggle class.

(<HTMLInputElement> this.confirmToggles[index].nativeElement) might be what you want, assuming that the native element really is a button of some sort. Of course, messing around with native elements isn't really the ideal Angular way of doing things.

If you want to get back instances of your MatButtonToggle class, you need to use @ViewChildren(MatButtonToggle).

baouss
  • 1,312
  • 1
  • 22
  • 52
kshetline
  • 12,547
  • 4
  • 37
  • 73
  • @ViewChildren(MatButtonToggle) would give me all the instances in the componenent, right? What if I want to only query those instances that have been tagged #confirm in the template? – baouss Feb 27 '18 at 11:51
  • Maybe @ViewChildren('confirm', {read: MatButtonToggle}) would do the trick? I can't seem to find good documentation of how the read parameter works, but it's supposed to give you some control over the type of objects returned. – kshetline Feb 27 '18 at 12:18