1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

FormBuilder with strongly typed form in ng14

Discussão em 'Angular' iniciado por ssougnez, Setembro 23, 2024.

  1. ssougnez

    ssougnez Guest

    I have the following form:

    const enum Fields {
    FirstName = 'firstName',
    LastName = 'lastName'
    }

    interface FormType {
    [Fields.FirstName]: FormControl<string | null>;
    [Fields.LastName]: FormControl<string | null>;
    }

    public form!: FormGroup<FormType>;

    this.form = new FormGroup({
    [Fields.FirstName]: new FormControl(null, { validators: Validators.required }),
    [Fields.LastName]: new FormControl(null, { validators: Validators.required }),
    });


    The usage of the enum is an habit I took to avoid mistyping.

    When I do this.form.getRawValue().firstName, the type of firstName is correctly defined as string | null. However, I prefer to use the FormBuilder to build my forms but I can't find a way to translate the form above using FormBuilder. I tried this:

    this.form = this._fb.group<FormType>({
    [Fields.FirstName]: ['', Validators.required],
    [Fields.LastName]: ['', Validators.required],
    });


    I could of course use a simple FormGroup without any type but it would defeat the purpose :p

    However, this does not even work as the inferred type of string | Validators. I tried different things without success.

    Is it possible to use the FormBuilder with the strongly typed forms?

    Continue reading...

Compartilhe esta Página