DEV Community

Vladislav
Vladislav

Posted on

New way to cook angular 14 typed forms

Hello everyone, I want to show you a library with which you can conveniently declare forms and describe the type of form according to your models, this will be useful to everyone who deals with forms in angular 14. ngx-mf i want to get some feedback from you, thanks! You can try it on stackblitz

You can do something like this:

We define some model:


enum ContactType {
    Email,
    Telephone,
}

interface IContactModel {
    type: ContactType;
    contact: string;
}

interface IUserModel {
    id: number;
    firstName: string;
    lastName: string;
    nickname: string;
    birthday: Date;
    contacts: IContactModel[];
}

Enter fullscreen mode Exit fullscreen mode

Then we define some magic type like:

Type Form = FormModel<IUserModel, { contacts: ['group'] }>
Enter fullscreen mode Exit fullscreen mode

Then we have type based on our model before form will be init:

FormGroup<{
    firstName: FormControl<string | null>;
    lastName: FormControl<string | null>;
    nickname: FormControl<string | null>;
    birthday: FormControl<Date | null>;
    contacts: FormArray<FormGroup<{
        type: FormControl<ContactType | null>;
        contact: FormControl<string | null>;
    }>>;
}>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)