[Fixed] Angular – How to detect if any of the elements in the child component are Touched in the Parent component

Issue

I am a beginner in Angular, I have got a Parent component and it has 3 child components inside it.

Inside the Parent component i have a Save button, my requirement is that if any of the elements or variables in any of the child components are touched then only i want the ‘Save’ button in the Parent component to be enabled.

<div>
<h3>Parent Component</h3>

<child-component1>
</child-component1>

<child-component1>
</child-component1>

<child-component1>
</child-component1>

<button type="submit" [disabled]="!isSaveButtonDisabled">
Save
</button>

</div>

Inside the parent component ts file.

public ischildComponentOneFormModified: boolean = false;
public ischildComponentTwoFormModified: boolean = false;
public ischildComponentThreeFormModified: boolean = false;

get isSaveButtonDisabled() : boolean {
  if(this.ischildComponentOneFormModified || this.ischildComponentTwoFormModified || this.ischildComponentThreeFormModified) {
return true;
}
else
{
return false;
}
}

Any inputs or suggestions on how do i achieve this ?

Solution

What you may want to use is an EventEmitter in your child component. When something changes (or component is "touched") then you emit from the child component and listen in your parent.

CHILD HTML

You have to configure how the touchDetected() method gets fired from your child component. There are several ways to accomplish this. Here is one example.

<div class="content-wrapper" (click)="touchDetected()">
   <h1>Hello, World!</h1>
</div>

CHILD CLASS

class ChildComponent {

   @Output() onChange: EventEmitter<any> = new EventEmitter<any>();

   touchDetected() {
     this.onChange.emit(true);
   }

}

PARENT HTML

<child-component (onChange)="listenForChildChange($event)" ></child-component>

PARENT CLASS

class ParentComponent {

   listenForChildChange(event:any) {
      this.ischildComponentFormModified = event;
   }
 
}

Leave a Reply

(*) Required, Your email will not be published