如何在角度6中默认选择Mat-Button-Toggle

时间:2019-03-14 04:44:00

标签: angular

我有一个6角形反应形式,其中使用了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>

我在ts文件中

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

但是在UI中,默认情况下未选择切换按钮。

请帮助,我在做什么错

我的模特就是这样

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

编辑:我也希望mat-button-toggle-group也与我的模型绑定。

1 个答案:

答案 0 :(得分:1)

Here是一个有效的示例:

HTML代码:

<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代码:

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(''), })
    });
  }
}