1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

Should Angular Form controls always be non-nullable?

Discussão em 'Angular' iniciado por David Mason, Outubro 9, 2024 às 11:33.

  1. David Mason

    David Mason Guest

    Since Angular introduced typed and also non-nullable form controls, I often hear the advise:


    "For all greenfield projects, please make controls always non-nullable, like this:

    With formbuilder:

    formGroupA = this.fb.nonNullable.group({
    User: [''],
    });


    With FormControl constructor:

    formGroupB = this.fb.nonNullable.group({
    User: new FormControl<EntraIdUserEntity | null>(null, {nonNullable: true}),
    });


    ie. this blog article states so.


    If you are developing a form “on a greenfield site”, we recommend that you set the nonNullable option to true for each control. This simplifies working with the generated data because the types reflect the actual input value. A normal input field, for example, always generates an empty string or a string with values.

    However, I do not think the advise is always valid, because in many scenarios a form should have initial values that are null:

    [​IMG]

    The picture shows a form with two selections and both should not have any default value.
    Therefore 'null' is the best initial value for those controls.

    The same applies for many others:

    • Date pickers
    • Radio buttons
    • Custom elements
    • Tree state checkboxes

    I understand that text fields should naturally start with an empty string '' and should be non-nullable because their initial value is "naturally" empty.

    But in many other cases, 'null' represents reality most acurately.

    Do you have some good counter arguments? :)

    Continue reading...

Compartilhe esta Página