我正在使用 Angular 材质。我有一个 mat-radio-group
和一个 mat-radio-button
我想默认选择一个单选按钮对象选项,但我不明白为什么它默认不选择。
这是我的代码。
app.component.ts
import { Component,EventEmitter,OnInit } from '@angular/core';
import { MatRadioChange } from '@angular/material/radio';
import { StudentService } from '../core/services/students.service';
export interface Student{
id: number;
name: string;
course: string;
avegareMarks: number;
}
export interface Students{
students: Student[];
bestStudent: Student;
}
@Component({
selector: 'app-component',templateUrl: './app-component.component.html',styleUrls: ['./app-component.component.scss']
})
export class AppComponent implements OnInit {
studentSelected!: Student;
students!: Students;
constructor(private studentsService: StudentsService) { }
ngOnInit(): void {
this.getStudents();
}
private getStudents(){
this.studentsService.findAll().subscribe((data:Students) => {
this.students = data.students;
this.studentSelected = data.bestStudent;
})
}
compareFn(c1: Student): boolean {
return c1 && this.studentSelected && c1.id === this.studentSelected.id && c1.name === this.studentSelected.name &&
c1.avegareMarks === this.studentSelected.avegareMarks && c1.course === this.studentSelected.course;
}
}
这是我的模板:
<div style="margin: 20px">
<mat-card style="max-width: 450px;">
<mat-card-subtitle>Students</mat-card-subtitle>
<mat-radio-group aria-labelledby="example-radio-group-label" class="example-radio-group"
[(ngModel)]="studentSelected">
<mat-radio-button class="example-radio-button"
*ngFor="let student of students" [value]="student" [checked]="compareFn(student)>
{{ student | json }}
</mat-radio-button>
</mat-radio-group>
</mat-card>
</div>