Angular – Displaying previous data when changing values in the form

I have a autocompete field which when selected displays details for the selected value on the right side of the form. The problem I have is when I clear the current value and select a new value the detail view diplays the previous details data instead of the new value’s details. Any help will be appreciated.

<mat-form-field class="full-wid mrgn-b-md" appearance="fill">
                                    <mat-label>{{'Product Name'|translate}}</mat-label>
                                    <input type="text"
                                           placeholder="Pick one"
                                                *ngFor="let option of filteredListOfProduct | async"
                                    <button type="button" mat-button *ngIf="form.get('gtin').value" matSuffix mat-icon-button aria-label="Clear"

TS file

displayFnGTIN(product: IProduct) {
    console.log('displayFnproduct', product);
    return product && product.brandname_en ? product.brandname_en : '';
onProductChange(ob) {
        console.log('Product changed...');
        console.log('this.selectedProduct    BEFORE',this.selectedProduct);
        this.selectedProduct = ob;
        console.log('this.selectedProduct    AFTER',this.selectedProduct);
clearGTINOption() {
        this.selectedProduct = null;

>Solution :

Its difficult to guess the right side of your form, which should look something like this.

<div *ngIf="selectedProduct">
  <p>Details: {{selectedProduct.details}}</p>

It is always a good idea to find the root cause why change detection is not working. But you can use following to manually trigger the change detection. Note: manual change detection invocation also comes with some performance implications. Mostly used when the property is used in non-angular code.

constructor(private cd: ChangeDetectorRef) {}

  onClearButtonClick() {
    this.selectedProduct = null;

    // Manually trigger a change detection cycle;

You can try this manual way whenever you are setting the new value to this.selectedProduct.
If the reference of the selectedProduct is changed, the change should reflect on the view by the change detection mechanism.

Leave a Reply