【问题标题】:Select rRadio Button by default angular material选择单选按钮默认角度材质
【发布时间】:2021-10-07 01:24:24
【问题描述】:

我正在使用 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>

【问题讨论】:

    标签: angular angular-material radio-button radio-group checked


    【解决方案1】:

    studentSelected 的默认值必须是来自this.students 的值之一,以便引用匹配选项之一。去掉 [checked] 和 compareFn,因为如果你这样做就不需要了:

    this.studentSelected = data.bestStudent 
        ? data.students.find(s => s.id === data.bestStudent.id) 
        : null;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-28
      • 2018-06-09
      • 2020-05-28
      • 2020-11-01
      • 1970-01-01
      • 2016-02-25
      • 1970-01-01
      • 2018-04-30
      相关资源
      最近更新 更多