首页 > 解决方案 > Angular8单选按钮检查功能意外运行

问题描述

我正在运行一个 Angular 8 Web 应用程序,其逻辑如下: HTML:

<div *ngFor="let item of selectedItems;">
  <input type="radio"
         [(ngModel)]="mySelectedItem"
         [value]="item.key"
         (ngModelChange)="setChangedItem($event)"
  />
  {{item.name}}
</div>

<tr *ngFor="let additionalItem of additionalItems">
      <td>
        <input type="checkbox" [value]="myAdditional" [checked]="setAdditionalItems(additionalItem)">
      </td>
      <td>{{additionalItem.name}}</td>
      <td>
</tr>

当我更改单选按钮时调用函数调用setAdditionalItems(这不是预期的)。在 component.ts 文件中找到

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

  //additionalItems: any[]=[];
  myAdditional='';
  primaryItemType: any[]=[];
  arrayStuff: any[]=[];

  selectedItems = [
    {name: 'FirstVal', key: 1, additionalInfo: 'The is first in the row'},
    {name: 'SecondVal', key: 2, additionalInfo: 'The is second in the row'},
  ];

  additionalItems = [
    {name: 'ThirdVal', key: 3, additionalInfo: 'The is third in the row'},
    {name: 'FourthVal', key: 4, additionalInfo: 'The is fourth in the row'},
    {name: 'FifthVal', key: 5, additionalInfo: 'The is fifth in the row'},
  ];

  mySelectedItem = this.selectedItems[0].key

  setAdditionalItems(additionalItem){
    console.log("ping!", additionalItem)
  }

  setChangedItem(changedItem){
    //some logic
    console.log('setChangedItem', changedItem)
    this.setTypeByItem(changedItem)
}

setTypeByItem(changedItem){
  this.primaryItemType = this.arrayStuff.filter(matchItem => {
    if(matchItem.key === changedItem){
      return matchItem.matchValue
    }
  });
  return this.primaryItemType
  }
}

我做错了什么?我没有看到对函数调用的任何其他调用setChangedItemsetAdditionalItems. 这可能是由于我的代码中的其他内容导致的错误,因为此代码库中的许多内容(不是我编写的)是紧密耦合的。

Stackblitz https://angular-qsiqor.stackblitz.io/

标签: javascriptangular

解决方案


问题是您的 [checked] 数据绑定指令。如果要在单击复选框时激活方法,则需要 (change) 指令。

这里是 Stackblitz。希望这对你有用,如果没有,请告诉我。

https://stackblitz.com/edit/angular-qnhbsn


推荐阅读