角度自动完成材料

时间:2019-06-30 07:36:00

标签: angular typescript angular-material

请帮助我修复错误。我想在表单中添加一个autocomplete材料和一个过滤器。

.ts 文件:

  contactArray;
  selectedContact: IContact;
  myControl = new FormControl();
  filteredContact: Observable<string[]>;

  constructor(private contactservice:ContactService,private _snackBar: MatSnackBar) { }

  ngOnInit() {

    this.filteredContact = this.myControl.valueChanges
    .pipe(
      startWith(''),
      map(value => typeof value === 'string' ? value : value.name),
      map(name => name ? this._filter(name) : this.contactArray.slice())
    );
    this.contactservice.getcontacts().subscribe(
      Response=>this.contactArray=Response
          );
  }
  displayFn(user?: IContact): string | undefined {
    return user ? user.name : undefined;
  }

  private _filter(name: string): IContact[] {
    const filterValue = name.toLowerCase();

    return this.contactArray.filter(contact => contact.name.toLowerCase().indexOf(filterValue) === 0);
  }
}

和我的 html 文件:

<mat-card>
  <form class="example-form">
    <mat-form-field class="example-full-width">
      <input type="text" placeholder="Assignee" aria-label="Assignee" matInput [formControl]="myControl" [matAutocomplete]="auto">
      <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
        <mat-option *ngFor="let contact of filteredContact | async" [value]="contact">
          {{contact.name}}{{contact.family}}
        </mat-option>
      </mat-autocomplete>
    </mat-form-field>
  </form>
</mat-card>

我的界面:

export interface IContact {
    cid:number;
    name:string;
    family:string;
    email:string;
    phone:number;
}

我的服务以便在json服务器中读取:

  url="http://localhost:3000/contacts";

  constructor(private http:HttpClient) { }

  getcontacts(){
    return this.http.get(this.url);
  }

  addcontacts(contact:IContact){
    return this.http.post(this.url,contact);
  }
}

我的错误是:

  

错误TypeError:无法读取未定义的属性“切片”

1 个答案:

答案 0 :(得分:2)

错误消息“无法读取未定义的属性”切片”,指出 变量'contactArray'不是数组。

尝试像这样将变量'contactArray'的类型声明为Array:

您的ts文件:

 contactArray: Array<Object> = [];
  selectedContact: IContact;
  myControl = new FormControl();
  filteredContact: Observable<string[]>;

  constructor(private contactservice:ContactService,private _snackBar: MatSnackBar) { }

  ngOnInit() {

    this.filteredContact = this.myControl.valueChanges
    .pipe(
      startWith(''),
      map(value => typeof value === 'string' ? value : value.name),
      map(name => name ? this._filter(name) : this.contactArray.slice())
    );
    this.contactservice.getcontacts().subscribe(
      Response=>this.contactArray=Response
          );
  }
  displayFn(user?: IContact): string | undefined {
    return user ? user.name : undefined;
  }

  private _filter(name: string): IContact[] {
    const filterValue = name.toLowerCase();

    return this.contactArray.filter(contact => contact.name.toLowerCase().indexOf(filterValue) === 0);
  }
}