我创建了一个带有 items 属性的 Angular 下拉列表组件,例如: 项目:任何 [];
此组件的用户能够将项目设置为任何内容的数组,例如:
[{id: "1", xyz: "hello"},{id: "2", xyz: "world}]
或
[{abc: "1", def: "john"},{abc: "2", def: "doe"}]
用户可以另外将 itemText 和 itemValue 设置为两个单独的属性:
在组件中,它们声明为:
项目文本:字符串;
项目值:字符串;
我正在尝试创建另一组名为customItemtext和customItemValue的属性。这将使用户能够将自定义选项添加到最初不属于数据源的 items 数组的开头。这里的问题是我需要在不知道属性名称的情况下推送项目,因为它们在技术上可以是任何东西。
我最初想只从itemText和itemValue属性中获取属性名称,但这是不可能的,因为用户可以在设置它们的值时使用格式。
注意:当用户设置项目数组时,它直接来自查询,因此用户无法灵活地自行添加自定义项目。它需要由我的组件通过属性完成。
哇,我刚刚构建了这个:InputTagComponent
发送预类型源时,它必须是对象数组。然后,与您类似,我使用filterKeys = ['firstName','lastName']
和displayKeys = ['firstName']
.
我不允许用户在使用对象时发送字符串。但你可以!
以下是我将用户选择的数据添加到表单数组的方法:
addTag(value: any):void {
// disallow blanks, duplicates, enforce maxTags limit and disallow string entries when displayKeys is set
if (
value == '' ||
this.maxTags === this.tagsArray.length ||
this.duplicates(value) ||
(this.displayKeys !== null && typeof value === 'string')
) { return; }
// if value is a string of comma-separated entries
if (typeof value === 'string' && value.includes(',')) {
for (let i = 0, j = value.split(",").length; i < j; i++) {
this.tagsArray.push(new FormControl(value.split(",")[i]));
this.onChange(this.tagsArray);
}
this.inputValue = '';
this.float = true;
return;
}
this.inputValue = '';
this.float = true;
this.tagsArray.push(new FormControl(value));
this.onChange(this.tagsArray); // update controller value
}
拆卸容易
removeTag(i: number):void {
this.tagsArray.removeAt(i);
this.onChange(this.tagsArray); // update controller value
}
对象的重复检查是字符串化的,这也比较字符串输入...
duplicates(value: any): boolean{
const test = JSON.stringify(value);
let match: boolean;
// test for duplicate objects in tag array
for ( let i = 0, j = this.tagsArray.value.length; i < j; i++ ) {
let controlVal = JSON.stringify(this.tagsArray.value[i]);
if (test === controlVal) {
return true;
} else {
match = false;
}
}
return match;
}
我希望这有所帮助,但如果我能提供更多帮助,请告诉我。 另外FWIW我在这里遇到了一个问题,你有任何见解:Angular的FormArray什么时候是传统数组,什么时候是FormArray对象?