typescript - autocompletado de material en angular
Por favor, ayúdame a corregir mi error. Quiero agregar un material autocomplete con un filtro a mi formulario.
Archivo .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);
}
}
y mi archivo 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>
mi interfaz :
export interface IContact {
cid:number;
name:string;
family:string;
email:string;
phone:number;
}
mi servicio para leer en json-server :
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);
}
}
mi error es :
ERROR TypeError: No se puede leer la propiedad 'slice' de undefined
Respuesta #1
El mensaje de error "No se puede leer la propiedad 'slice' de undefined" indica que el valor de la variable 'contactArray' no es un arreglo.
Intenta declarar el tipo de la variable 'contactArray' como Array de esta manera:
tu archivo 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);
}
}
