Reputation: 21
Please help me to fix my error. I want to add a autocomplete
material with a filter to my form.
.ts file :
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);
}
}
and my html file :
<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>
my interface :
export interface IContact {
cid:number;
name:string;
family:string;
email:string;
phone:number;
}
my service for read in 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);
}
}
my error is :
ERROR TypeError: Cannot read property 'slice' of undefined
Upvotes: 2
Views: 931
Reputation: 21
The Error message "Cannot read property 'slice' of undefined" stating that the value of the variable 'contactArray' is not an array.
Try to declare the type of variable 'contactArray' to Array like this:
your ts file :
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);
}
}
Upvotes: 2