Taking on the role of an Angular developer, my task involves receiving a JSON-entity from an API and assigning its values to a FormGroup
. Despite everything working as expected (with all values present in the FormGroup
), the issue lies with the visual preselection of values in the mat-select
.
All the functionality mentioned above is encapsulated within the onInit()
method.
product-group-update.component.ts: full code: https://pastebin.com/hXLqBAcF
export class ProductGroupUpdateComponent implements OnInit {
NO_PRODUCT: string = 'No product';
editProductGroupForm: FormGroup;
id: number;
isFormSubmitted = false;
availableProducts: Product[];
toSelect: Product[];
constructor(
private formBuilder: FormBuilder,
private productGroupService: ProductGroupService,
private productService: ProductService,
private router: Router,
private activatedRoute: ActivatedRoute,
private location: Location,
) {
}
ngOnInit(): void {
this.editProductGroupForm = this.formBuilder.group({
name: ['', [Validators.required, Validators.maxLength(100)]],
description: ['', [Validators.required, Validators.maxLength(100)]],
products: ['', []],
});
this.activatedRoute.paramMap.subscribe(params => {
this.id = +params.get('id');
this.productGroupService.getProductGroupById(this.id).subscribe(
receivedProductGroup => {
this.toSelect = receivedProductGroup.products;
this.editProductGroupForm.setValue({
name: receivedProductGroup.name,
description: receivedProductGroup.description,
products: receivedProductGroup.products,
});
}
);
});
console.log(this.editProductGroupForm)
this.productService.getAllProducts(new Page<Product>()).subscribe(response => {
this.availableProducts = response.content;
});
}
...
}
product-group-update-component.html full code: https://pastebin.com/9GqyU2r2
<div class="col-md-12">
<div class="card card-container">
<form (ngSubmit)="submitForm()" [formGroup]="editProductGroupForm" class="new-obj-form" id="register-form">
...
<mat-form-field appearance="fill" class="example-full-width">
<mat-label>Products</mat-label>
<mat-select formControlName="products" multiple [(value)]="toSelect">
<mat-option [value]="NO_PRODUCT">{{NO_PRODUCT}}</mat-option>
<mat-option *ngFor="let product of availableProducts" [value]="product">
{{product.name}}
<i><small>(ID: {{product.id}})</small></i>
</mat-option>
</mat-select>
</mat-form-field>
...
</form>
</div>
</div>
The issue arises when attempting to visually preselect values using mat-select: https://i.sstatic.net/BZ889.png
Additional code snippets:
export interface Product {
id: number;
name: string;
description: string;
price: number;
groupId: number;
sold: boolean;
}
import {Product} from "./product";
export interface ProductGroup {
id: number;
name: string;
description: string;
products: Product[];
}