javascript - 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
}
}
我做错了什么?我没有看到对函数调用的任何其他调用setChangedItem
或setAdditionalItems
. 这可能是由于我的代码中的其他内容导致的错误,因为此代码库中的许多内容(不是我编写的)是紧密耦合的。
Stackblitz https://angular-qsiqor.stackblitz.io/
解决方案
问题是您的 [checked] 数据绑定指令。如果要在单击复选框时激活方法,则需要 (change) 指令。
这里是 Stackblitz。希望这对你有用,如果没有,请告诉我。
推荐阅读
- linux - 为什么这个程序会收到 SEGV?
- node.js - Node.js 和 Gulp:真正的管道序列可能与书面的 '.pipe()' 链不同?
- kotlin - 空块和单元有什么区别
- c# - Serilog 是否在配置日志级别时自动捕获日志
- java - Gradle 多项目传递依赖
- excel - 如何在python中将一列数据传输到具有多列的一行中?
- react-router-v4 - 如何在路由器之外访问“match.params”?
- php - 如何在godaddy服务器上上传一组图像?
- c - STM32F7 - 从 RAM 和闪存执行代码
- php - 如何用单个字符串替换嵌套或多级数组的选择器