raju
raju

Reputation: 6936

How to select the mat-button-toggle by default in angular 6

I have a reactive angular-6 form, in which I have used mat-button-toggle-group

<mat-button-toggle-group #group="matButtonToggleGroup"  [(value)]="myFlagForButtonToggle" (change)="onEndpointValChange(group.value)"  multiple=false formControlName='endpoints' [(ngModel)]="myFlagForButtonToggle">
          <mat-button-toggle  *ngFor="let item of endpointToggleOptions;" [value]="item">{{item}}</mat-button-toggle>
</mat-button-toggle-group>

In ts file I have

  myFlagForButtonToggle: String[] = ["Single"];
  endpointToggleOptions: Array<String> = ["Single", "Multiple"];

But in the UI no of the toggle button is selected by default.

Please help, what I am doing wrong

My Model is like this

this.outerForm = this._formBuilder.group({
  firstFormGroup: this._formBuilder.group({
    pidNumber: ['', [Validators.pattern(this.spacePattern)]],
  }),
  secondFormGroup: this._formBuilder.group({
    endpoints: ['', [Validators.required]]
  })
});

EDIT: I want mat-button-toggle-group to bind with my model also.

Upvotes: 3

Views: 11947

Answers (1)

Prashant Pimpale
Prashant Pimpale

Reputation: 10707

Here is a working example:

HTML Code:

<form [formGroup]="outerForm">
    <div formGroupName="secondFormGroup">
        <mat-button-toggle-group #group="matButtonToggleGroup" (change)="onEndpointValChange(group.value)" multiple="false" formControlName='endpoints'
         [(ngModel)]="myFlagForButtonToggle">
            <mat-button-toggle *ngFor="let item of endpointToggleOptions;" [value]="item">{{item}}</mat-button-toggle>
        </mat-button-toggle-group>
    </div>
</form>

TS Code:

import { Component } from '@angular/core';

import { FormGroup, FormBuilder, Validators, FormControl } from '@angular/forms';

/**
 * @title Exclusive selection
 */
@Component({
  selector: 'button-toggle-exclusive-example',
  templateUrl: 'button-toggle-exclusive-example.html',
  styleUrls: ['button-toggle-exclusive-example.css'],
})
export class ButtonToggleExclusiveExample {

  myFlagForButtonToggle: String = "Single";
  endpointToggleOptions: Array<String> = ["Single", "Multiple"];
  outerForm: FormGroup;
  constructor(private _formBuilder: FormBuilder) {
    this.outerForm = this._formBuilder.group({
      firstFormGroup: this._formBuilder.group({ pidNumber: new FormControl(''), }), secondFormGroup:
        this._formBuilder.group({ endpoints: new FormControl(''), })
    });
  }
}

Upvotes: 5

Related Questions