Angular 6单击单选按钮不会更新ngModel

问题描述 投票:1回答:2

我有一个广播组:

<div class="btn-group">
  <div class="btn btn-outline-secondary"
  *ngFor="let category of categories">
    <input
    type="radio"
    [value]="category.id"
    [(ngModel)]="categoryModel.name">
     {{category.name}}
  </div>
</div>

TS

import { Component, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.scss'],

})

export class Test {

  categories: {};
  categoryModel = {name: ''};

  constructor(private modalService: NgbModal) {
    this.categories = [{
      id: 1, name: 'test1',
    },
    {
      id: 2, name:  'test2'
    },
    {
      id: 3, name:  'test3',
    },
  ]
}

当我点击我的收音机时,我的模型没有更新,{{categoryModel.name}}仍然是空的,它有什么问题,我怎么能改变它?

angular data-binding ngfor angular2-ngmodel
2个回答
0
投票

您绑定到radiobutton的值,该值等于类别的id。

您可以使用change事件获取当前所选类别的名称,如:

change(category_id){
 this.categoryModel.name = this.categories.find(c => c.id == category_id).name
}

这里有一个例子:https://stackblitz.com/edit/angular-qeejnn?file=src%2Fapp%2Fapp.component.ts


0
投票

你可以绑定categoryModel.name而不是绑定categoryModel。要使其工作,请将选项值设置为category并确保单选按钮具有相同的name

<div class="btn-group">
  <div *ngFor="let category of categories" class="btn btn-outline-secondary">
    <input
      type="radio"
      name="category"
      [value]="category"
      [(ngModel)]="categoryModel">
      {{category.name}}
  </div>
</div>

有关演示,请参阅this stackblitz

© www.soinside.com 2019 - 2024. All rights reserved.