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

Strongly Typed Reactive Form: Correct usage?

Discussão em 'Angular' iniciado por Gabriel, Setembro 15, 2024.

  1. Gabriel

    Gabriel Guest

    I am currently experimenting with Strongly Typed Reactive Forms in Angular.

    I have defined an interface:

    interface Data {
    name: string;
    mobile: number;
    isAdmin: boolean;
    }`


    And here is my component:

    export class ReactiveComponent implements OnInit {

    form!: FormGroup<{
    name: FormControl<string>;
    mobile: FormControl<number>;
    isAdmin: FormControl<boolean>;
    }>;

    ngOnInit(): void {
    this.form = new FormGroup({
    name: new FormControl<string>('', {
    nonNullable: true,
    validators: [Validators.required],
    }),
    mobile: new FormControl<number>(0, {
    nonNullable: true,
    validators: [Validators.required],
    }),
    isAdmin: new FormControl<boolean>(false, { nonNullable: true }), // Boolean field
    });
    }

    addValues() {
    const name = this.form.get('name').value;
    const mobile = this.form.get('mobile').value;
    console.log(name + mobile);
    }
    }


    I am trying to ensure type saftey, attempting to add name and mobile is my test however I am not getting the expected compilation errors: TS18048: name is possibly undefined TS18048: mobile is possibly undefined

    1. How can they possibly be undefined if ive declared their type as number and string respectively
    2. Shouldn't there be a type error when trying add string and number
    3. Is it possible to elimnate some of this boiler plate using formBuilder / nonNullableFormBuiler class instances through dependency injection?

    Cheers

    Continue reading...

Compartilhe esta Página