Search code examples
angularangular6angular2-changedetection

How to detect the changes in @input attribute when the same value is sent from parent


I researched and none of them was able to give me correct solution for the problem. I have 2 components named parentComponent and childComponent.

childComponent.html

     <div *ngIf="isShowMessage">
       <p>Hey i was told by parent component to be shown Here i am !!!</p>
         <button (click)="cancel()">cancel</button>
     </div>

childComponent.ts

     _isShowMessage = false;

     @Input() set isShowMessage(value: boolean) {
          this._isShowMessage = value;
     }
      get isShowMessage(): boolean {
            return this._isShowMessage;
      }
     cancel(): void {
      this._isShowMessage = false;
      this.isShowMessage = false;
    }

ParentComponent.html

      <childComponent [isShowMessage]="isShowMessage"></childComponent>
      <button (click)="handleClick()">save</button>

ParentComponent.ts

        isShowMessage = false;
        handleClick(): void {
          this.isShowMessage = true;
         }

Step 1: when i click save button from parent , child component div is shown:

     <p>Hey i was told by parent component to be shown Here i am !!!</p>

Step2: When i click cancel button from child component, the div is hidden. [expected Behavior]

step 3: when i again click save button from parent , child component div is NOT shown.

is it due to same value true sent second time as well? not sure ... any suggestion appreciated.


Solution

  • Consider this approach:

    ParentComponent.html

    <childComponent #child></childComponent>
    <button (click)="handleClick(child)">save</button>
    

    ParentComponent.ts

    handleClick(child): void {
      child.isShowMessage = true;
    }