htmlangularformsangular-reactive-formsangular-forms

How to send data from a component with no use of button to its parent in angular


I have host component and inside it there's three components(children). First child has a form with no submit button, while second child has again a form with submit button, Plus third child has just a plain text. Host component is rendering these children + a button that will send data gathered from forms to BE.

so the problem is when trying to use eventEmitter in second child it works fine I get data in host(parent), but in first child no, because there's no button to fire the eventEmmitter

so my question is how to send data from the first child if there's no button, is there any way to achieve that? or I should follow another strategy to do such thing child-two.component.html:

<form [formGroup]="teamForm">
<h4 class="title form-title">Basic Team Info</h4>

<!-- // TEAM NAME  -->
<div class="flex-column">
  <span class="label">Team Name</span>
  <mat-form-field appearance="outline">
    <input type="text" matInput placeholder="Taco Teams"formControlName="team_name" />
  </mat-form-field>
</div>

<!-- // CONTACT Number  -->
<div class="flex-row">
  <div class="flex-column">
    <span class="label">Team Contact Number</span>
    <mat-form-field appearance="outline">
      <input type="text" matInput placeholder="+84 2763 3627" formControlName="team_contactNum" />
      <mat-icon class="icon" matPrefix>call</mat-icon>
    </mat-form-field>
  </div>

  <!-- CATEGORY  -->
  <div class="flex-column">
    <span class="label">Category</span>
    <mat-form-field appearance="outline">
      <input type="text" matInput placeholder="UNDER 17" formControlName="team_category" />
      <mat-icon class="icon" matPrefix>location_on</mat-icon>
    </mat-form-field>
  </div>
</div>
and my host.component.html is like this:
 <section class="parent">
     <div class="div1">
    <app-child-one></app-child-one>

    <app-child-two (OpenPlayerFormEvent)="isPlayerFormOpenFn($event)"></app-child-two>

    @if (isPlayerFormOpen) { <app-child-three></app-child-three> }

    <div class="add-team-btn-container">
      <a href="/somewhere..." class="skip-btn" href="">add teams later</a>
    // this button will use all data from childreen 1 and 2 and send it to BE
      <button class="add-team-btn" mat-flat-button (click)="add_team()"> Add team </button>
    </div>

  </div>
</section>

Solution

  • you could use reference to the first child in the template or via viewChild in the component ts if you wish

     <app-child-one #childOne></app-child-one>
    ...
    (click)="add_team(childOne.teamForm.getRawValue())"
    

    here childOne is a component instance and you can access all the methods/fields of it