You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中mat-radio按钮全局联动及卡片删除等问题求助

Angular问题解决方案

问题1:所有卡片单选按钮联动选中

原因:所有mat-radio-group都绑定到组件全局的valueFromRadio变量,导致选中状态被所有卡片共享。

解决:给每个Card对象添加独立的选中状态属性(比如selectedValue),让每个卡片的单选组绑定到自身的该属性,实现状态隔离。

问题2:提交后移除当前卡片

原因:原代码中this.cards[i]==null是比较操作而非赋值,无法修改卡片状态;且直接修改数组元素后,Angular可能无法检测到变更。

解决:通过*ngFor的索引参数获取当前卡片位置,用splice直接从数组中移除该元素,触发Angular变更检测更新视图。

问题3:card.question参数无法正常工作

原因:自定义decode函数递归调用自身导致无限循环;且opentdb返回的是HTML实体编码字符串(如"),需要正确解码才能显示正常文本。

解决:实现正确的HTML实体解码逻辑,替换递归调用的错误写法。


修改后的home.component.html

<div class="grid grid-cols-5 gap-4 pt-10">
  <div *ngFor="let card of cards; let i = index" class="">
    <div *ngIf="card; else nil">
      <mat-card>
        <mat-card-header>
          <mat-card-title>{{decode(card.question)}}</mat-card-title>
          <mat-card-subtitle>Type: {{card.type}} , Difficulty: {{card.difficulty}}</mat-card-subtitle>
        </mat-card-header>
        <mat-card-content>
          <mat-radio-group aria-label="Select an option" [(ngModel)]="card.selectedValue">
            <mat-radio-button class="p-2" [value]="1">{{decode(card.correct_answer)}}</mat-radio-button>
            <mat-radio-button [value]="0" class="p-2" *ngFor="let incorrect_answer of card.incorrect_answers">
              {{decode(incorrect_answer)}}
            </mat-radio-button>
          </mat-radio-group>
        </mat-card-content>
        <button mat-button type="submit" (click)="getAns(card.selectedValue, card.question, i)">Submit</button>
      </mat-card>
    </div>
    <ng-template #nil></ng-template>
  </div>

  <h1 class="w-screen text-8xl">Score: {{count}}</h1>
</div>

修改后的home.component.ts

const route:string="https://opentdb.com/api.php?amount=10"
export class Card{
  constructor(public category:string,
              public type:string,
              public difficulty:string,
              public question:string,
              public correct_answer:string,
              public incorrect_answers:string[],
              public selectedValue?: number) { // 添加独立选中状态属性
  }
}
export class ResponseApi{
  constructor(public response_code:number,
              public results:Card[]) {
  }
}
export class HomeComponent implements OnInit {
  fetchedData: ResponseApi ={
    response_code:1,
    results:[]
  };
  count=0
  cards:Card[]=[]
  answer: number[]=[];
  constructor(private http:HttpClient) { }

  getAns(value:number, question:string, index:number){
    console.log("question:", question)
    if (value === 1){
      this.count++
    }
    // 直接从数组中移除当前卡片
    this.cards.splice(index, 1);
  }

  private fetchData(){
    this.http.get<any>(route).subscribe(
      res=>{
        this.fetchedData=res
        // 给每个Card实例添加selectedValue属性
        this.cards = this.fetchedData.results.map(card => ({...card, selectedValue: null}));
        console.log("cards:", this.cards)
      }
    );
  }

  ngOnInit(): void {
    this.fetchData()
  }

  // 正确解码HTML实体
  decode(s: string) {
    const txt = document.createElement("textarea");
    txt.innerHTML = s;
    return txt.value;
  }
}

内容的提问来源于stack exchange,提问作者SOHAM

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 17:35:18