加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

如何使用* ngFor过滤Angular中未知数量的元素?

发布时间:2020-12-17 10:25:06 所属栏目:安全 来源:网络整理
导读:我需要创建一个搜索输入来过滤每个父帐户中的子帐户列表.目前,输入任一输入都会过滤所有帐户,而不是仅关联相关帐户. 实例(StackBlitz) Basic (no FormArray) With FormArray 要求 帐户和子帐户的数量未知(1 … *) 每个帐户都需要HTML中自己的搜索输入(FormCo
我需要创建一个搜索输入来过滤每个父帐户中的子帐户列表.目前,输入任一输入都会过滤所有帐户,而不是仅关联相关帐户.

实例(StackBlitz)
Basic (no FormArray)
With FormArray

要求

>帐户和子帐户的数量未知(1 … *)
>每个帐户都需要HTML中自己的搜索输入(FormControl)
>输入输入A应仅筛选帐户A的列表.
输入输入B应仅过滤帐户B的列表.

问题

>如何确保每个FormControl仅过滤当前* ngFor上下文中的帐户?
>如何独立观看未知数量的FormControls以进行价值变化?我意识到我可以观看FormArray,但我希望有更好的方法.

理想情况下,解决方案应该:

>使用反应表格
>当值发生变化时发出一个Observable
>允许动态地从表单添加/删除FormControls

这是我解决问题的方法.

首先,您遍历外部帐户并为每个帐户创建一个专用的formControl并将它们存储在FormGroup中.作为ID参考,我使用了帐号.有了这个,我声明了一个名为getSearchCtrl(accountNumber)的函数来检索正确的formControl.

使用[formControlName] =“account.accountNumber”将模板与FormGroup中提供的formControl连接.

使用getSearchCtrl(account.accountNumber)将正确的formControl引用到过滤器管道并传递该值.

< div * ngFor =“let subAccount of account.subAccounts | filter:'accountNumber':
getSearchCtrl(account.accountNumber).价值;让我=索引“>
<跨度> {{subAccount.accountNumber}}< /跨度>
< / DIV>

我还编辑了你的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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读