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

Typed Angular form with formbuilder and null as initial value

Discussão em 'Angular' iniciado por David Mason, Outubro 7, 2024.

  1. David Mason

    David Mason Guest

    I want to make use of typed forms in Angular.
    In my scenario I have a form group that should have some properties.
    All of them should be nullable and start with an initial value of "null".
    But they should also be typed.

    I also want to use the form builder to make my code short & concise.

    However, I am failing to do what I want.

    One of my approaches looks like this:

    formGroup = this.fb.group<{
    User: FormControl<string | null>,
    Site: FormControl<string | null>,
    AccessLevel: FormControl<string | null>,
    Application: FormControl<string | null>,
    BusinessProcessArea: FormControl<string | null>,
    }>({
    User: [null, Validators.required],
    Site: [null, Validators.required],
    AccessLevel: [null, Validators.required],
    Application: [null, Validators.required],
    BusinessProcessArea: [null, Validators.required],
    });


    However, typescript does not like what I am doing and throws an error here.
    Also I need to double all the properties what makes this piece of code also hard to maintain.

    I would love to do something like this:

    formGroup = this.fb.group({
    User<string>: [null, Validators.required],
    Site<string>: [null, Validators.required],
    AccessLevel<string>: [null, Validators.required],
    Application<string>: [null, Validators.required],
    BusinessProcessArea<string>: [null, Validators.required],
    });


    I know that this is not valid Typescript and that I cannot put the type definition there.

    But this should show my wish to:

    • Allow nullable fields
    • That are at the same time typed fields (ie: string|null)
    • That do not need to be repeated
    • That can use form builder to have a concise and clear syntax

    How can I achieve this?

    Continue reading...

Compartilhe esta Página