【问题标题】:Angular 6 clicked radio button doesn't update ngModelAngular 6 单击的单选按钮不会更新 ngModel
【发布时间】:2019-02-14 23:25:00
【问题描述】:

我有一个广播组:

<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


    【解决方案1】:

    //工作代码,您可以直接复制粘贴代码并根据需要自定义

    import { Component } from '@angular/core';
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
    
      categoryList: {};
      selectedCategory = { name: "" };
    
      constructor() {
        this.categoryList = [
          { id: 1, name: 'Option1' },
          { id: 2, name: 'Option2' },
          { id: 3, name: 'Option3' },
          { id: 4, name: 'Option4' },
          { id: 5, name: 'Option5' },
        ]
      }
    }
    <div>
    <h1>  Seleted Option:  {{selectedCategory.id}}- 
      {{selectedCategory.name }}</h1>
      <div class="btn btn-outline-secondary"
      *ngFor="let cat of categoryList">
        <input
        type="radio"
        [value]="cat"
        [(ngModel)]="selectedCategory">
         {{cat.name}}
      </div>
    </div>

    【讨论】:

    • 酷,谢谢 :) 虽然我还必须为单选按钮添加名称属性,以便浏览器知道它们属于同一个按钮组
    【解决方案2】:

    您可以绑定categoryModel,而不是绑定categoryModel.name。要使其正常工作,请将选项值设置为 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 以获取演示。

    【讨论】:

      【解决方案3】:

      您正在绑定到等于类别 id 的单选按钮的值。

      您可以使用更改事件来获取当前选择的类别的名称,例如:

      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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-14
        • 2019-02-05
        • 1970-01-01
        • 1970-01-01
        • 2019-07-25
        • 1970-01-01
        相关资源
        最近更新 更多