I'm working on a angular application but I ran into a problem I cant find the solution to. I'm trying to patch some preselected values to a form control (mat-select multiple) but it just wont show the values. It works fine with the control above (food), but when I try to bind to the multiple choice list, the values wont show.
//Here is my code:
@Component({
selector: 'app-add-edit',
templateUrl: './add-edit.component.html',
styleUrls: ['./add-edit.component.less']
})
export class AddEditComponent implements OnInit {
pageTitle = '';
order: Order;
filteredUsers: User[] = [];
id: number;
orderToDisplay: Order = new Order();
orderForm: FormGroup = new FormGroup({
food: new FormControl('', [Validators.required]),
usersOrdering: new FormControl('', [Validators.required])
});
constructor(private dialogRef: MatDialogRef<AddEditComponent>,
private ordersService: OrdersService,
@Inject(MAT_DIALOG_DATA) public data: any,
private fb: FormBuilder) { }
usersSelected: User[];
ngOnInit(): void {
this.id = this.data.orderId;
if (this.id == 0) {
this.pageTitle = 'Add a new order';
this.order = new Order();
} else {
this.pageTitle = 'Edit the order';
this.getOrder(this.id);
}
this.filterUsers(this.id);
}
save(): void {
if (this.orderForm.valid) {
if (this.orderForm.dirty) {
this.usersSelected = this.orderForm.controls['usersOrdering'].value;
if (this.id == 0) {
this.order.food = this.orderForm.controls['food'].value;
this.order.orderCount = this.usersSelected.length;
this.order.restaurantId = this.data.restaurantId;
this.order.usersOrdering = this.usersSelected;
this.ordersService.addOrder(this.order)
.subscribe(data => {
this.dialogRef.close(true);
});
} else {
this.order.id = this.id;
this.order.food = this.orderForm.controls['food'].value;
this.order.orderCount = this.usersSelected.length;
this.order.usersOrdering = this.usersSelected;
this.ordersService.updateOrder(this.order)
.subscribe(data => {
this.dialogRef.close(true);
});
}
}
} else
console.log('form is invalid')
}
dismiss(): void {
this.dialogRef.close(false);
}
displayOrder(o: Order): void {
if (this.orderForm) {
this.orderForm.reset();
}
this.order = o;
console.log(this.order.usersOrdering);
this.orderForm.patchValue({
food: this.order.food,
usersOrdering: this.order.usersOrdering
});
this.orderForm.updateValueAndValidity();
}
filterUsers(orderId: number) {
this.ordersService.filterUsers(orderId)
.subscribe(data => {
this.filteredUsers = data;
});
}
getOrder(id: number) {
this.ordersService.getOrder(id)
.subscribe(data => {
this.order = data;
this.displayOrder(this.order);
});
}