Во-первых, вы должны использовать несколько классов, которые отражают структуру вашего Json.
Вот короткий пример:
user.ts:
import { PersonalInformation } from './personal-information';
export class User {
_id: string;
email: string;
createdAt: number;
updatedAt: number;
personalInformation: PersonalInformation;
someOtherInformation: SomeOtherInformation
}
personal-information.ts:
import { Address } from './address';
import { Country } from './country';
export class PersonalInformation {
avatarUrl?: URL;
firstName?: string;
lastName?: string;
birthDate?:string;
countryOfResidence?: Country;
address?: Address;
phone?: number;
};
И определите каждый вложенный объект, используя ту же логику.
Затем, чтобы уменьшить сложность родительского компонента, вы можете вкладывать вложенные компоненты и управлять ими.проверка некоторых полей в них:
parent-component.ts:
let someInformation: SomeInformation = this.sharedService.user.someInformation;
this.parentFormGroup = this.formBuilder.group({
countryCtrl: someInformation.accountCountry : '', Validators.required],
child: this.formBuilder.group({
accountNumberCtrl: ['', [ Validators.required, Validators.minLength(5)]], >>>> YOU CAN SET VALUES FOR YOUR FORM BY REPLACING ''
[...]
}),
additionalInformationCtrl: [(userBankingInformation) ? userBankingInformation.additionalInformation : '']
});
parent-component.html:
<form [formGroup]="parentFormGroup" (ngSubmit)="onSubmit(parentFormGroup)">
<div>
<country-search-input [parent]="parentFormGroup" [countries]="countries" [title]="title"></country-search-input>
[...]
<div formGroupName="child">
<account-information [parent]="parentFormGroup.controls.child"></account-information>
</div>
child-component.ts:
export class ChildComponent {
@Input()
parent: FormGroup
// You can do some of the work here
}
child-component.html:
<div class="some-class-name" [formGroup]="parent">
<mat-form-field class="some-information-form">
<input matInput type="text" pattern="[a-zA-Z0-9-]+" placeholder="Account number" formControlName="accountNumberCtrl" required>
</mat-form-field>
[...]
</div>
Вы можете создавать и добавлять собственные валидаторы в другие файлы, если вам это нужно.Надеюсь, это поможет.Удачи.