I'm trying to implement an autocomplete input field using Angular Material which is sourcing a list of users from a backend server.
I've managed to get the data into the autocomplete dropdown and the filtering working. Unfortunately, when an item is selected from the drop down, it's not displayed in the input box.
Controller:
export class SignalMutateComponent implements OnInit {
visible = true;
selectable = true;
removable = true;
addOnBlur = true;
readonly separatorKeysCodes: number[] = [ENTER, COMMA];
options: User[] = []
filteredOptions: Observable<User[]>;
assigneeId = new FormControl();
private _signalMutate: Signal;
@Input() set signalMutate(signalMutate: Signal) {
this._signalMutate = signalMutate
this.signalForm.patchValue(signalMutate);
if(signalMutate.labels) {
this.labels = signalMutate.labels.split(',');
if(this.labels[0] == "") {this.labels.shift();}
} else {
this.labels = [];
}
}
get signalMutate() {
return this._signalMutate
}
signalForm: FormGroup;
loading = false;
submitted = false;
error: string;
formSignalValue: Signal;
labels: [string] = [];
constructor(
private formBuilder: FormBuilder,
private router: Router,
private authenticationService: AuthenticationService,
private userService: UserService,
private signalService: SignalService,
private snackBar: MatSnackBar
) { }
ngOnInit() {
this.userService.getFiltered("active")
.subscribe(users => {this.options = users as User[]; });
this.signalForm = this.formBuilder.group({
title: [''],
description: ['', Validators.required],
problem: ['', Validators.required],
value: ['', Validators.required],
requestor: ['', Validators.required],
labels: [''],
id:[''],
assigneeId: ['']
});
this.filteredOptions = this.assigneeId.valueChanges
.pipe(
startWith(''),
map(value => typeof value === 'string' ? value : this.updateAssignee(value)),
map(fullName => fullName ? this._filter(fullName) : this.options.slice())
);
}
displayFn(user?: User): string | undefined {
return user ? user.fullname : undefined;
}
private _filter(name: any): User[] {
console.log("name");
console.log(name);
const filterValue = name.toLowerCase();
console.log(filterValue);
return this.options.filter(option => option.fullName.toLowerCase().indexOf(filterValue) === 0);
}
updateAssignee(id: number) {
console.log('yes: '+id);
this.signalForm.patchValue({assigneeId: id});
}
....
HTML File:
<div class="uk-width-1-1">
<mat-form-field class="formFieldWidth700">
<input type="text" placeholder="Assignee" aria-label="Assignee" matInput [formControl]="assigneeId" [matAutocomplete]="auto" [ngClass]>
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
<mat-option *ngFor="let option of filteredOptions | async" [value]="option.id">
{{option.fullName}}
</mat-option>
</mat-autocomplete>
</mat-form-field>
</div>
Any help would be appreciated!
Thank you