I use form builder to build a form and using get to obtain the value of birthday, ageNum and ageUnit, but it seems that this method is not working cuz it may got null in group age. does anyone know how to fix this? thanks
ts
this.form = this.fb.group({
birthday: ['', this.validateDate],
age: this.fb.group(
[
{
ageNum: [],
ageUnit: [AgeUnit.Year]
},
{validator: this.validateAge('ageNum', 'ageUnit')}
])
})
const birthday = this.form.get('birthday');
const ageNum = this.form.get('age').get('ageNum'); //here got wrong
const ageUnit = this.form.get('age').get('ageUnit'); //and here
html
<div [formGroup]="form" class="age-input">
<div>
<mat-form-field>
<input type="text" matInput [matDatepicker]="birthPicker" formControlName="birthday" placeholder="birthDate">
<mat-datepicker-toggle [for]="birthPicker" matSuffix></mat-datepicker-toggle>
<mat-error>date error</mat-error>
</mat-form-field>
<mat-datepicker touchUi="true" #birthPicker></mat-datepicker>
</div>
<ng-container formGroupName="age">
<div class="age-num">
<mat-form-field>
<input type="number" placeholder="age" matInput formControlName="ageNum">
</mat-form-field>
</div>
<div>
<mat-button-toggle-group formControlName="ageUnit" [(ngModel)]="selectedUnit">
<mat-button-toggle *ngFor="let unit of ageUnits" [value]="unit.value">
{{unit.label}}
</mat-button-toggle>
</mat-button-toggle-group>
</div>
<mat-error *ngIf="form.get('age').hasError('ageInvalid')">age or unit error</mat-error>
</ng-container>
</div>
component.htmlfile ?[and]when create the formGroup -unless you want a formArray-.3.- (optional) you can use "dot notation":const ageNum = this.form.get('age.ageNum')