Search code examples
angulartypescriptangular7angular-forms

How To Submit Angular Form with a Nested Component


I have a dateTime component that I built that I am going to use throughout an application. I have a formGroup that I am using to submit a form on a separate component, and I need this component to be a part of that form. I can't seem to get the data from the child form to show in the parentForm. Is there a way to set this as a property/ value of the parent form?

Child DateTime Picker HTML:

<mat-form-field>
  <input matInput [ngxMatDatetimePicker]="picker" placeholder="{{ name }}" [formControl]="dateControl" required="true">
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <ngx-mat-datetime-picker #picker startView="year"></ngx-mat-datetime-picker>
</mat-form-field>

Child Typescript:

@Input() name: string;
@Input() displayTime: boolean;
@Input() allowDateInPast: boolean;

public dateControl = new FormControl();

constructor() { }

ngOnInit() {

}

Parent HTML/form:

<form [formGroup]="formGroup">
<mat-label>Name</mat-label>
    <input type="textfield" formControlName="reportName" matInput required="true" placeholder="Report Name" name="reportName">
</mat-form-field>

<div class="col-sm">
    <app-datetime-picker [name]="'Start Date'" [displayTime]="true" [allowDateInPast]="true"></app-datetime-picker>
</div>

<button class="float-right" [disabled]="formGroup.invalid" (click)="createReport()" mat-raised-button color="primary">Save</button>
  </div>
</form>

Parent Typescript:

formGroup: FormGroup = new FormGroup({

reportName: new FormControl("", Validators.required),
// ?? something here
});

Is this possible? Would I need to use @Output() in some manner?

Thanks for any help.
Travis W-


Solution

  • What I usually do is I pass the FormControl down as an input. So on the child component you have an input: @Input() dateControl: FormControl;

    In your parent html you pass down the FormControl like: <app-datetime-picker [dateControl]="formGroup['dateControl'] >

    You can now read the properties of the FormControl in the parent component just as normal.

    I do agree with the other answers as well, control value accessor would be a good solution for this, but a bit harder to implement.