0

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>
4
  • Can you show component.html file ? Commented Aug 11, 2022 at 1:50
  • Okay, I just posted it, thank you for remind me this. Commented Aug 11, 2022 at 2:24
  • I think that it need to you. stackblitz.com/edit/formbuilder?file=app%2Fapp.component.html Commented Aug 11, 2022 at 2:34
  • 1
    1.**not** use ngModel and formControlName in the same tag, 2.remove the [ and ] when create the formGroup -unless you want a formArray-.3.- (optional) you can use "dot notation": const ageNum = this.form.get('age.ageNum') Commented Aug 11, 2022 at 7:13

1 Answer 1

0

In short, you could try following syntax for getting the value of a FormControl inside a FormGroup:

const ageNum = this.form.get(['age', 'ageNum']).value;
const ageUnit = this.form.get(['age', 'ageUnit']).value;

However, a similar question has already been answered, go there for more possiblities and details: How to get Nested formgroup's controls in angular

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.