【问题标题】:Material autocomplete not displaying list on click点击时材料自动完成不显示列表
【发布时间】:2026-01-18 20:30:01
【问题描述】:

我有一个材料自动完成功能。

我正在调用 ngrx 来提取数据。

 //parentcomponent.ts
 this.store.select(fromStore.getSearchFormStateMessageTypeListData).subscribe(msgTypeList => {
  if (msgTypeList.length > 0) {
    console.log('msgtypelist ='+msgTypeList)
    for (var i = 0; i < msgTypeList.length; i++) {
      this.messageTypeList.push(msgTypeList[i]);
    }
  }
  else {
    this.store.dispatch(new fromStore.GetGlobalSearchMessageTypeList({}));
  }
})


//parentcomponent.html

 <mat-card style="margin: 1px;">
    <search-form [messageTypeList]="messageTypeList"  (onSearchData)="searchButtonClick($event)" [rowData]="rowData | async">
   </search-form>
</mat-card>

从父级我将 msgTypeList 传递给子级。

在孩子中,我将自动完成绑定到列表,但是当我们单击内部时,列表没有显示任何内容。

它只在我们在输入框中输入内容时显示选项(过滤选项)

 //childcomponent.html
 <form [formGroup]="searchForm" id="searchForm" style="width:100%;height:70%" (ngSubmit)="onSubmit()">
<tr>
<td class="input-form" style="padding-right:4%;width:10%">
   <mat-form-field>
     <input type="text" placeholder="Message Type" aria-label="Assignee"  formControlName="msgType" matInput [matAutocomplete]="autoMsgType">
     <mat-autocomplete #autoMsgType="matAutocomplete" placeholder="Message Type" [displayWith]="displayMessageTypeFn">
          <mat-option *ngFor="let messageType of filteredMessageTypeList | async | sort:'msgType'" [value]="messageType">{{messageType.msgType}}</mat-option>
       </mat-autocomplete>
  </mat-form-field>
 </td>
</tr>
</form>

下面是child.ts文件

   //childcomponent.ts
searchForm: FormGroup;

  ngOnInit() {
this.searchForm = this.formBuilder.group({
      direction: [null],
      msgType: [null, Validators.nullValidator],
     });
    this.filterMessageTypeLists();
     }



filterMessageTypeLists() {
    this.filteredMessageTypeList = this.searchForm.controls['msgType'].valueChanges.pipe(
      startWith<string | any>(''),
      map(value => typeof value === 'string' ? value : value.msgType),
      map(msgType => msgType ? this._msg_filter(msgType, this.messageTypeList) : this.messageTypeList.slice())
    );
  }


     private _msg_filter(msgType: string, lists: any[]): any[] {
    const filterValue = msgType.toLowerCase();
    return lists.filter(option => option.msgType.toLowerCase().includes(msgType.toLowerCase()))
      }

  displayMessageTypeFn(field?: any): string | undefined {
return field ? field.msgType : undefined;;
 }

问题是,如果我点击自动完成输入,它应该会打开列表但没有显示

但是,如果我们在输入框中输入任何内容,则会显示选项

【问题讨论】:

  • 我必须先将空字符串设置为 formControl,以便在输入任何内容之前显示自动完成下拉列表:this.searchForm.controls['msgType'].setValue('');

标签: angular list autocomplete angular-material angular6


【解决方案1】:

我遇到了同样的问题。

确保 this.messageTypeList 在 map() 调用期间包含值

我的问题是我的数组中没有任何内容,因此显示为空白。

ngOnInit() {
// I subscribed to messageTypeList; 
// Then I did my control.onValueChanged( map... map...);
}

应该是

ngOnInit() {
  ObservableList.subscribe(array => {
     messageTypeList = array;
     control.onValueChanged( // do your mapping filter stuff);
  });
}

只要列表中有值,它就会显示出来。

【讨论】:

    【解决方案2】:

    您可以在 ngAfterViewInit 生命周期挂钩中简单地设置 searchForm 的值

    ngAfterViewInit(): 无效 { this.searchForm .setValue(''); }

    【讨论】:

      【解决方案3】:

      您只需在获取数据后调用 form.valueChanges,而不是像这样在 init 函数中执行它:

      this.data1.getArticleS().subscribe(a => {
              this.tabArticle = a;
              console.log(a);
              this.filteredArticles = this.stockForm.get('article').valueChanges //erreur angular qui fonctionne bug interpreter ?
                  .pipe(
                      startWith(''),
                      map(value => typeof value === 'string' ? value : value.name),
                      map(name => name ? this._filter(name) : this.tabArticle.slice()));
      
          });
      

      【讨论】:

        【解决方案4】:

        在你的 html 中的输入上绑定一个点击事件,并在点击事件上调用一个函数。像这样的:

        <input type="text" placeholder="Message Type" aria-label="Assignee"  formControlName="msgType" 
            matInput [matAutocomplete]="autoMsgType" (click)="myFunc()" >
        

        并在您的 ts 文件中,声明一个布尔变量并最初将其设置为 false。假设变量是bool

        现在编写函数 myFunc() 并简单地切换该变量,如下所示:

        this.bool = !this.bool;
        

        现在在您的 matautocomplete 标记中,只需将 panelOpen 属性设置为 bool 变量,如下所示:

        <mat-autocomplete #autoMsgType="matAutocomplete" placeholder="Message Type" [displayWith]="displayMessageTypeFn" 
             panelOpen="bool">
        

        您可以在以后的某些函数中将bool 变量设置回false,以使其正常工作。

        【讨论】:

        • 我找到了问题,但需要找到解决方案。 filterMessageTypeLists 函数中的值更改属性仅在输入框中输入某个值时触发。我需要让它允许列表在页面加载时加载
        • 你可以使用 setvalue 代替 valueChanges。
        【解决方案5】:

        我正在使用

        <mat-option *ngFor="let option of filteredRecipients | async" ...
        

        ngOnInit(): void {
            this.filteredRecipients = this.myControl.valueChanges
              .pipe(
                startWith(''),
                map(value => this.chatService.filterForAutoComplete(value))
              );
         }
        

        问题是我的视图(以及因此this.filteredRecipients)在this.chatService 实际收到地图函数试图获取的收件人列表之前被呈现。因此,我使用以下方法来确保在 map 函数运行之前填充收件人。

        为我服务:

        private vAllRecipientsPopulatedSubject = new Subject<any>();
        public allRecipientsPopulated$ = this.vAllRecipientsPopulatedSubject.asObservable();
        public setRecipients(rcpts: RecipientModel[]) {
            const callback = () => {
              this.vAllRecipientsPopulatedSubject.next();
            };
            this.vAllRecipients = [];
            let itemsProcessed = 0;
            rcpts.forEach(element => {
              this.vAllRecipients.push(element);
              itemsProcessed++;
              if (itemsProcessed === rcpts.length) {
                callback();
              }
            });
        }
        

        在我的控制器中

        this.filteredRecipients = combineLatest([this.myControl.valueChanges.pipe(startWith('')), this.chatService.allRecipientsPopulated$])
          .pipe(
            map(([changes, notused]) => this.chatService.filterForAutoComplete(changes))
          );
        

        【讨论】:

          最近更新 更多