[英]How to get the value of nested form with get in formbuilder?
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.我使用表单生成器来构建表单并使用get获取生日、ageNum 和 ageUnit 的值,但似乎这种方法不起作用,因为它可能在 group age 中得到null 。 does anyone know how to fix this?
有谁知道如何解决这一问题? thanks
谢谢
ts 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 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>
In short, you could try following syntax for getting the value of a FormControl inside a FormGroup:简而言之,您可以尝试以下语法来获取 FormGroup 中的 FormControl 的值:
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但是,已经回答了一个类似的问题,go 那里有更多的可能性和细节: How to get Nested formgroup's controls in angular
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.