如何使用* ngFor过滤Angular中未知数量的元素?
我需要创建一个搜索输入来过滤每个父帐户中的子帐户列表.目前,输入任一输入都会过滤所有帐户,而不是仅关联相关帐户.
实例(StackBlitz) 要求 >帐户和子帐户的数量未知(1 … *) 问题 >如何确保每个FormControl仅过滤当前* ngFor上下文中的帐户? 理想情况下,解决方案应该: >使用反应表格
这是我解决问题的方法.
首先,您遍历外部帐户并为每个帐户创建一个专用的formControl并将它们存储在FormGroup中.作为ID参考,我使用了帐号.有了这个,我声明了一个名为getSearchCtrl(accountNumber)的函数来检索正确的formControl. 使用[formControlName] =“account.accountNumber”将模板与FormGroup中提供的formControl连接. 使用getSearchCtrl(account.accountNumber)将正确的formControl引用到过滤器管道并传递该值. < div * ngFor =“let subAccount of account.subAccounts | filter:'accountNumber': 我还编辑了你的stackblitz app:https://stackblitz.com/edit/angular-reactive-filter-4trpka?file=app%2Fapp.component.html 我希望这个解决方案能帮到你. import { Component,OnInit } from '@angular/core'; import { FormBuilder,FormGroup,FormControl } from '@angular/forms'; @Component({ selector: 'my-app',templateUrl: './app.component.html',styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { searchForm: FormGroup; searchTerm = ''; loaded = false; // Test Data. The real HTTP request returns one or more accounts. // Each account has one or more sub-accounts. accounts = [/* test data see stackblitz*/] public getSearchCtrl(accountNumber) { return this.searchForm.get(accountNumber) } constructor() { const group: any = {} this.accounts.forEach(a => { group[a.accountNumber] = new FormControl('') }); this.searchForm = new FormGroup(group); this.loaded = true; } ngOnInit() { this.searchForm.valueChanges.subscribe(value => { console.log(value); }); } } <ng-container *ngIf="loaded; else loading"> <div [formGroup]="searchForm"> <div *ngFor="let account of accounts; let ind=index" class="act"> <label for="search">Find an account...</label> <input id="search" [formControlName]="account.accountNumber" /> <div *ngFor="let subAccount of account.subAccounts | filter : 'accountNumber': getSearchCtrl(account.accountNumber).value; let i=index"> <span>{{subAccount.accountNumber}}</span> </div> </div> </div> </ng-container> <ng-template #loading>LOADING</ng-template> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |