angular 2 md-options使用md-autocomplete进行奇怪的UI行为

时间:2017-09-21 11:04:05

标签: angular angular-material2 md-autocomplete

enter image description here按照https://material.angular.io/components/autocomplete的指南进行操作 我试图在我的应用程序中实现自动完成功能,它需要从后端服务获取自动完成建议,所有逻辑工作正常。但我对md-options的一些奇怪的UI行为完全无能为力。而不是显示下面的选项在输入字段中,选项显示在页面底部。请参考屏幕截图。任何想法背后的原因以及如何解决它。

my component.ts:

private searchTerms = new Subject<string>();

// Push a search term into the observable stream.
search(term: string): void {
  this.searchTerms.next(term);
}

private userNameField: FormControl = new FormControl();

private filteredUsers: Observable<any[]>;

   ngOnInit() {

      this.userNameField.valueChanges
         .startWith(null)
         .forEach(term => {
             if(!this.utils.isEmptyString(term)) {
                this.search(term);
             }
        });

        this.filteredUsers = this.searchTerms
        .debounceTime(300)        // wait 300ms after each keystroke before considering the term
        .distinctUntilChanged()   // ignore if next search term is same as previous
        .switchMap(term => term   // switch to new observable each time the term changes
          // return the http search observable
          ? this.userService.searchUser(term)
          // or the observable of empty heroes if there was no search term
          : Observable.of<any[]>([]))
        .catch(error => {
          // TODO: add real error handling
          console.log(error);
          return Observable.of<any[]>([]);
        });

         this.filteredUsers.subscribe(
            function (x) {
                console.log('Next: ' + x.toString());
            },
            function (err) {
                console.log('Error: ' + err);
            },
            function () {
                console.log('Completed');
            });
   }

我的template.html:

<form class="example-form">
    <md-form-field class="example-full-width">
      <input name="userName" type="text" placeholder="Search user by name, email or mobile"
             mdInput [formControl]="userNameField" [mdAutocomplete]="auto">
      <md-autocomplete #auto="mdAutocomplete">
        <md-option *ngFor="let user of filteredUsers | async" [value]="user.name">
          {{ user.name }}
        </md-option>
      </md-autocomplete>
    </md-form-field>

1 个答案:

答案 0 :(得分:0)

花了很少时间,终于知道我需要将材质样式表添加到我的index.html:

    <!-- angular material style sheet -->
<link href="https://unpkg.com/@angular/material/prebuilt-themes/indigo-pink.css" rel="stylesheet">,

现在一切都运转良好,:))