-1

I have this mat-toggle-group:

<mat-button-toggle-group #group="matButtonToggleGroup">
  <mat-button-toggle value="specific">
      Specific
    </mat-button-toggle>
    <mat-button-toggle value="general" checked>
        General
      </mat-button-toggle>                
</mat-button-toggle-group>

and i have these 2 fields.

<div *ngIf="group.value == specific">
<mat-form-field id="id">
  <input matInput placeholder="Insert seed Id">
</mat-form-field>
<mat-form-field id="id">
      <input matInput placeholder="Insert affiliate rank">
    </mat-form-field>
  </div>

As you can see in the second code snippet i'm trying to include the fields in the DOM only when Specific has been selected. However this does not work. I've read here How to access Angular 2 template variable in ngIf that the template variable is not accessible outside the template element and that i should use @ViewChild instead. I found this tutorial on how to use ViewChild https://blog.angular-university.io/angular-viewchild/. But its about referencing a component (ColorSampleComponent) that has been made by the user himself. I am trying to reference my buttontogglegroup like so:

  @ViewChild(matButtonToggleGroup)
    group: matButtonToggleGroup;

But it doesn't work because i can't import matButtonToggleGroup, i can only import the module but thats not the same thing.

Can anyone give me some pointers on how to get the value of the togglegroup for use in the ngIf directive? Thank you

Maurice
  • 6,698
  • 9
  • 47
  • 104
  • are these fields inside of a form? if so, which form manipulation technique are you using(template driven, reactive, dynamic)? If you're new to forms, start by reviewing the [Forms](https://angular.io/guide/forms) and [Reactive Forms](https://angular.io/guide/reactive-forms) guides. – alphapilgrim Jul 31 '18 at 15:04
  • I am using reactive forms, but i guess i'll use the ngModel directive mentioned by rip – Maurice Jul 31 '18 at 15:20
  • id recommend using reactive forms, its just way more performant. – alphapilgrim Jul 31 '18 at 15:22

1 Answers1

1

You can simply use NgModel here with two way binding:

<mat-button-toggle-group [(ngModel)]="toggleValue" #group="matButtonToggleGroup">
<...>
<div *ngIf="toggleValue === 'specific'">

And also, of course define toggleValue:

export class YourComponent {

toggleValue;
gizmo
  • 191
  • 1
  • 11