繁体   English   中英

为什么我不能 select 在此 Angular Material 应用程序中添加单选按钮?

[英]Why can't I select a radio button in this Angular Material app?

我一直在用 Angular 14 和 Angular Material 开发电子商务应用程序。

我正在处理一个注册表单,其中包含一组单选按钮。

在表单组件的 Typescript 文件中,我有:

import { FormService } from '../../services/form.service';

export class FormComponent implements OnInit {

  constructor (
    private formService: FormService
  ) { }

  public accountTypes!: any;
  public selectedAccountType: any;
  
  
  ngOnInit(): void {
    this.getAccountTypes();
  }
  
   public setAccountType() {
    this.selectedAccountType = this.accountTypes[0].value;
  };

  public getAccountTypes() {
    this.formService.getAccountTypes().subscribe(response => {
      this.accountTypes = response;
      if (this.accountTypes && this.accountTypes.length) {
        this.setAccountType();
      } 
    });
  }
  
}

在模板中:

<mat-radio-group name="account_type" [(ngModel)]="this.selectedAccountType">
    <mat-radio-button *ngFor="let accountType of accountTypes" value="accountType.value" [checked]="accountType.checked">
        <span class="top-label">{{ accountType.label }}</span>
    </mat-radio-button>
</mat-radio-group>

问题

由于我无法理解的原因,当我单击(单选)按钮时,它不会保持选中状态。

问题

  1. 我究竟做错了什么?
  2. 达到预期结果的最简单和最可靠的方法是什么?

使用mat-radio-buttonngModel你不需要处理checked属性。 在你的情况下,它总是用false覆盖它。 你可以在官方文档中阅读很多内容。 这是正确的方法( Stackblitz ):

HTML:

<mat-radio-group class="example-radio-group" [(ngModel)]="favoriteSeason">
  <mat-radio-button class="example-radio-button" *ngFor="let season of seasons" [value]="season">
    {{season}}
  </mat-radio-button>
</mat-radio-group>
<div class="example-selected-value">Your favorite season is: {{favoriteSeason}}</div>

和代码:

@Component({
  selector: 'radio-ng-model-example',
  templateUrl: 'radio-ng-model-example.html',
  styleUrls: ['radio-ng-model-example.css'],
})
export class RadioNgModelExample {
  favoriteSeason: string;
  seasons: string[] = ['Winter', 'Spring', 'Summer', 'Autumn'];
}

value属性更改为属性绑定,即[value]而不是value ,这在使用ngModel时是必需的。

ngModel通过比较[value][(ngModel)]绑定来决定选择什么。

那是带有selectedAccountTypemat-radio-button[value]

您可以删除checked的,因为它不适用于ngModel并且默认选项已在setAccountType()方法中设置。

 <mat-radio-group name="account_type" [(ngModel)]="this.selectedAccountType"> <mat-radio-button *ngFor="let accountType of accountTypes" [value]="accountType.value"> <span class="top-label">{{ accountType.label }}</span> </mat-radio-button> </mat-radio-group>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM