[英]Angular: How can i select 2 radio buttons between 2 radio groups in 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>
由于我无法理解的原因,当我单击(单选)按钮时,它不会保持选中状态。
使用mat-radio-button
和ngModel
你不需要处理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)]
绑定来决定选择什么。
那是带有selectedAccountType
的mat-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.