使用[checked]属性相应地向列表添加或删除值不会按预期工作



我创建了一个stackBlitz来展示功能。

https://stackblitz.com/edit/angular-ivy-nbmvfn?file=src/app/app.component.ts

我有两个不同的列表,具有不同的对象结构,我需要根据初始列表中返回的内容相应地选中复选框,通过添加值来更新列表,然后在我的应用程序中保存它(而不是在stackblitz中(。

目前它的行为不正常,我已经创建了一个方法来检查是否应该在onInit时预先检查复选框,但当从列表中添加或删除(选中复选框(对象时,它要么没有被删除,要么另一个复选框索引被取消选中。到目前为止,我的全部解决方案都在stackBlitz中。

问题出在哪里?我该如何解决这种行为?

不能将字符串value与对象obj的内容进行比较。您必须深入对象并直接比较字符串。更新的onChange方法:

onChange($event, object) {
const value = $event.target.value;
const isChecked = $event.target.checked;
const item = {
uri: value,
};
if (isChecked === true) {
this.userEndpoints.push(item);
console.log(item);
} else if (isChecked === false) {
let index = -1
this.userEndpoints.forEach((endpoint, idx) => {
if (endpoint.uri === value) {
index = idx
}
if (index > -1) {
return
}
})
this.userEndpoints.splice(index, 1);
console.log(this.userEndpoints);
} else console.log('Failed');
}

分叉堆叠式

不要浪费时间跟踪两个列表,而是将这两个列表合并为一个列表,请在下面找到一个实现示例。

ts

import { Component, OnInit } from '@angular/core';
import { AllEndpoints } from './all-endpoints';
import { UserEndpoints } from './user-endpoints';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit {
endpointList: AllEndpoints[];
userEndpoints: UserEndpoints[];
ngOnInit(): void {
this.userEndpoints = [{ uri: '/home' }, { uri: '/information' }];
this.endpointList = [
{ endpoint: '/home', method: 'GET' },
{ endpoint: '/login', method: 'GET' },
{ endpoint: '/information', method: 'GET' },
];
this.endpointList.forEach((item) => {
const found =
this.userEndpoints.find((x) => x.uri === item.endpoint) || null;
item.checked = !!found;
});
}
onChange($event, object) {
const value = $event.target.value;
const isChecked = $event.target.checked;
const obj = eval(`this.${object}`);
const item = {
uri: value,
};
if (isChecked === true) {
obj.push(item);
} else if (isChecked === false) {
obj.splice(obj.indexOf(value), 1);
} else console.log('Failed');
console.log(obj);
return obj;
}
isChecked(endpoint: string): boolean {
return !!this.userEndpoints.find((x) => x.uri === endpoint);
}
save() {
alert(
`items to be saved ${JSON.stringify(
this.endpointList.filter((x) => x.checked)
)}`
);
}
}

html

<form (submit)="save()">
<label for="enabledEndpoints">Enabled Endpoints</label>
<div *ngFor="let item of endpointList">
<input
type="checkbox"
[id]="item.endpoint"
[value]="item.endpoint"
name="enabledEndpoints"
[checked]="item.checked"
(change)="item.checked = !item.checked"
/>
<label [for]="item.endpoint"> {{ item.endpoint }}</label>
</div>
<span>{{ endpointList | json }}</span>
<button type="submit">save</button>
</form>

分叉堆叠式

最新更新