gpt4 book ai didi

angular - 如何在 Angular 6 中过滤 FormArray 元素

转载 作者:行者123 更新时间:2023-12-05 06:24:59 24 4
gpt4 key购买 nike

我想通过在文本框中键入文本来过滤表单数组,将过滤表单数组中的数据并返回匹配的行。

这是 a link这是我试图实现的 stackblitz 链接。我有数千个表单数组元素,我想过滤它并从下拉列表中选择相应的值,然后单击更新按钮将更新所有记录。


@Component({
selector: 'app-form-array',
templateUrl: './form-array.component.html',
styleUrls: ['./form-array.component.css']
})
export class FormArrayComponent implements OnInit {
form: FormGroup;
searchText: String = '';
devices: Array<any> = [];
datasets: Array<any> = [];
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
published: true,
credentials: this.fb.array([]),
});
}
ngOnInit() {
this.devices = [
{ name: 'device1' },
{ name: 'device2' },
{ name: 'device3' },
{ name: 'device4' },
{ name: 'device5' },
{ name: 'device6' }
];
this.datasets = [
{ name: 'dataset1' },
{ name: 'dataset2' },
{ name: 'dataset3' },
{ name: 'dataset4' },
{ name: 'dataset5' },
{ name: 'dataset6' }
];
this.devices.forEach((device) => {
this.addCreds();
});
}
addCreds() {
const creds = this.form.controls.credentials as FormArray;
creds.push(this.fb.group({
dataset_name: ['', []],
device_id: ['', []],
}));
this.devices.push({ name: 'device'+ (this.devices.length+1) });
}
submit() {
console.log(this.form.value.credentials);
}
}
<form [formGroup]="form" *ngIf="form">
<input type="checkbox" formControlName="published"> Published
<div *ngIf="form.controls.published.value">

<h2>Credentials</h2>
<button (click)="addCreds()">Add</button>
<button (click)="submit()">submit</button>
<br><br>
<input placeholder="search device" [(ngModel)]="searchText" [ngModelOptions]="{standalone: true}">
<br><br>
<div formArrayName="credentials" *ngFor="let creds of form.controls.credentials?.value | formArrayFilterPipe: searchText; let i = index">
<ng-container [formGroupName]="i">
<table>
<tbody>
<tr>
<td>
{{devices[i]?.name}}
</td>
<td>
<select id="{{datasets[i]?.name + 'choice'}}" formControlName="dataset_name">
<option *ngFor="let dataset of datasets">{{dataset?.name}} </option>
</select>
</td>
</tr>
</tbody>
</table>
</ng-container>
</div>

</div>
</form>```






最佳答案

检查这个

表单数组过滤器管道.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
name: 'formArrayFilterPipe'
})
export class FormArrayFilterPipe implements PipeTransform {

transform(items: any[], searchText: string): any[] {
if(!items) return [];
if(!searchText) return items;

searchText = searchText.toLowerCase();
return items.filter( it => {
console.log('abc', it.value.device_id);
return it.value.device_id.toLowerCase().includes(searchText);
});
}

}

输出 enter image description here

更新此代码并检查。如有任何疑问,请告诉我。

关于angular - 如何在 Angular 6 中过滤 FormArray 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57392183/

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