gpt4 book ai didi

javascript - 如何在 Angular 中删除双向数据绑定(bind) -2/4

转载 作者:数据小太阳 更新时间:2023-10-29 04:03:26 26 4
gpt4 key购买 nike

我正在 Angular 中开发一个多选下拉菜单,它也有搜索功能。那是当我通过我的主数据解析从输入字段给出的输入并仅在 DOM 中显示过滤后的内容时。这是我的功能:

modifyFilter(value: any) {
console.log('value', value); //The value passed from DOM
this.filterContent = this.catalogManufacturerNames; /******/
for(let i=0; i<this.catalogManufacturerNames.length;i++) {
/* Search catalogManufacturerNames for the value and splice all
filterContent not having the matching value */
}
}

代码的问题在于,每次调用 modifyFilter 方法时,catalogManufacturerNames 也会随 filterContent 一起更改。因此,每次我调用 modifyFilter 时,标记为/******/filterContent 的行都会分配给前一个 filterContent,而不是全局且可能未更改的 catalogManufacturerNames。我认为问题是 filterContentcatalogManufacturerNames 有两种绑定(bind)方式,但我不知道如何根据我的要求修改它。或者有没有其他方法可以解决这个问题。欢迎提出建议。

最佳答案

在这种情况下,您必须使用Object.assignDeepCopy。它将创建您的对象/变量的副本,因此当您对主要对象执行任何过滤器时,它不会反射(reflect)在复制的对象中,反之亦然。

您可以根据需要使用 {},[]

{}:用于单个对象

[]:用于对象的集合

let copiedItem = Object.assign({}, copiedItem , PrimaryItem );

详情请引用:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

选项:2 深拷贝

DeepCopy(obj: any): any {
let clonedObject;

if (obj === null || typeof obj !== 'object') {
return obj;
}
if (obj instanceof Array) {
clonedObject = [];
for (let i = 0; i < obj.length; i++) {
clonedObject[i] = this.deepCopy(obj[i]);
}
return clonedObject;
}
if (obj instanceof Date) {
clonedObject = new Date(obj.valueOf());
return clonedObject;
}
if (obj instanceof RegExp) {
clonedObject = RegExp(obj.source, obj.flags);
return clonedObject;
}
if (obj instanceof Object) {
clonedObject = new obj.constructor();
for (const attr in obj) {
if (obj.hasOwnProperty(attr)) {
clonedObject[attr] = this.deepCopy(obj[attr]);
}
}
return clonedObject;
}
}

组件调用

let copiedItem: any[] = this.DeepCopy(PrimaryItem );

关于javascript - 如何在 Angular 中删除双向数据绑定(bind) -2/4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44795040/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com