英文:
Reset Mat Radio Group's Mat Radio Buttons to default on a button click
问题
我有一组项目需要使用单选按钮进行评分。我使用了Mat Radio Group和Mat Radio按钮。就像下面这样,我需要对游戏进行好坏或无评分。应用更改后,所有单选按钮都应默认为"None"。请帮助我完成这个任务。
模板
<ng-container *ngFor="let s of sites">
<div class="col-sm-12 col-md-5">
{{s}}
</div>
<div class="col-sm-12 col-md-7">
<mat-radio-group>
<mat-radio-button *ngFor="let o of options; let j=index"
[checked]="j===0"
[value]="o">
{{o}}
</mat-radio-button>
</mat-radio-group>
</div>
</ng-container>
<button (click)="resetRadio()">应用更改</button>
TypeScript 代码
export class App {
sites: string[] = ['Tekken', 'Street Fighter', 'DBZ'];
options: string[] = ['None', 'Good', 'Bad'];
resetRadio(): void {
}
}
英文:
I have a set of items to be rated using radio button. I used Mat radio group and Mat radio buttons. Like below, I have to rate games good bad or none. After applying the changes all the radio buttons should be defaulted to None. Please help me to complete this task.
Template
<ng-container *ngFor="let s of sites">
<div class="col-sm-12 col-md-5">
{{s}}
</div>
<div class="col-sm-12 col-md-7">
<mat-radio-group>
<mat-radio-button *ngFor="let o of options; let j=index"
[checked]="j===0"
[value]="o">
{{o}}
</mat-radio-button>
</mat-radio-group>
</div>
</ng-container>
<button (click)="resetRadio()">Apply Changes</button>
TypeScript code
sites: string[] = ['Tekken', 'Street Fighter', 'DBZ'];
options: string[] = ['None', 'Good', 'Bad'];
resetRadio(): void {
}
答案1
得分: 1
最好、简单且安全的方法是使用Angular 模板驱动表单或响应式表单...但根据您的要求,您可以使用 @ViewChildren 装饰器来定位 MatButtonGroup 并设置 'None' 值。
这是一个示例:stackblitz
英文:
The best, easy and safe way is to use Angular template driven forms or Reactive Forms...but for your requirement you can use @ViewChildren decorator to target MatButtonGroup and set 'None' value.
this is an example : stackblitz
答案2
得分: 1
使用formGroup,您可以使用
private form: FormGroup = new FormGroup({....});
resetRadio(): void {
this.form.reset();
}
英文:
Using formGroup, you can use
private form: FormGroup = new FormGroup({....
resetRadio(): void {
this.form.reset();
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论