如何防止清除下拉菜单中先前选择的值?我在FormArray中使用MatSelectSearch

问题描述 投票:0回答:1

我正在尝试在FormArray内的下拉菜单中实现MatSelectSearch。我想我快要到了,但是我遇到的问题是在为第一行选择一个值之后,我添加了另一行并再次开始搜索,第一行的值似乎清除了,直到我完成键入或选择为止第二行的值。

我制作了StackBlitz来演示我的问题。

感谢您的帮助!

angular select angular-material dropdown formarray
1个回答
2
投票

改善我的评论。

首先将filter_admin_advocacy声明为数组

//see that is simple an empty array
public filter_admin_advocacy: ReplaySubject<any[]>[] = [];

更改函数initializeAdminAdvocacyFilter。我们使用此函数为this.filter_admin_advocancy [i]

赋值。

还有,我们使用“ startWith”管道强制下一个-else首先,我们得到一个空列表-

initializeAdminAdvocacyFilter(i) {
    //declare the filter_admin_advocacy[i]
    this.filter_admin_advocacy[i] = new ReplaySubject<any[]>(1);

    const adminAdvocacy = <FormArray>this.type.controls['selected_interests'];
    adminAdvocacy.controls[i].get('admin_advocacy_filter_ctrl').valueChanges
    .pipe(
      takeUntil(this._onDestroy),
      //it's important the startWith
      startWith(adminAdvocacy.controls[i].get('admin_advocacy_filter_ctrl').value))
    .subscribe(() => {
      this.filterAdminAdvocacies(i);
    });
  }

filterAdminAdvocacies函数,我们将this.filter_admin_advocacy替换为this.filter_admin_advocacy [i]

filterAdminAdvocacies(i) {
    if(!this.advocacies) {
      return;
    }

    // get the search keyword
    const adminAdvocacy = <FormArray>this.type.controls['selected_interests'];

    let search = adminAdvocacy.controls[i].get('admin_advocacy_filter_ctrl').value;

    if(!search) {
      //HERE
      this.filter_admin_advocacy[i].next(this.advocacies.slice());
      return;
    } else {
      search = search.toLowerCase();
    }

    // filter the gender_titles
    //and HERE
    this.filter_admin_advocacy[i].next(
      this.advocacies.filter(advocacies => advocacies.advocacy.toLowerCase().indexOf(search) > -1)
    );

  }

在ngOnInit中,在initializeForm之后,调用以初始化initializeAdminAdvocacyFilter(0)

  this.initializeForm();
  this.initializeAdminAdvocacyFilter(0)

  //and remove the this.filter_admin_advocacy.next
  //the startWith in the subscribe make the work 
  //    this.filter_admin_advocacy[0].next(this.advocacies.slice()); 

过滤器中最后使用的数组

  <mat-option *ngFor="let advocacy of filter_admin_advocacy[i] | async" 
       [value]="advocacy.id">
       {{ advocacy.advocacy }}
  </mat-option>

I forked the stackblitz

© www.soinside.com 2019 - 2024. All rights reserved.