Angular reactive Form error: Must supply a value for form control with name:

后端 未结 3 2100
南方客
南方客 2020-12-17 08:42

I premise I am very novice with angular. I am trying to implement an angular reactive form, but I am encountering this error: \"Must supply a value for form control with nam

相关标签:
3条回答
  • 2020-12-17 09:03

    Unfortunately 'undefined' isn't allowed, you need to set each property to 'null'.

    It's perfectly legitimate to have a property set to undefined, common when coming directly from the server.

    You can convert properties before calling setValue with something like this:

       // set all 'missing' OR 'undefined' properties to null
            const newValue: any = {...value};
    
            for (const field in this.controls) { 
    
                if (newValue[field] === undefined) {
                    newValue[field] = null;
                }
            }
    
            super.setValue(newValue, options);
    

    Watch out because JSON.stringify() will remove undefined, and so if you use that to send a value back to your server you need to make sure it can handle missing properties there.

    0 讨论(0)
  • 2020-12-17 09:14

    This error can appear if you're using setValue on a formGroup but not passing in a value for every control within that group. For example:

    let group = new FormGroup({
      foo: new FormControl(''), 
      bar: new FormControl('')
    });
    group.setValue({foo: 'only foo'}); //breaks
    group.setValue({foo: 'foo', bar: 'bar'}); //works
    

    If you truly want to only update some of the controls on the group, you can use patchValue instead:

    group.patchValue({foo: 'only foo, no problem!'});
    

    Docs for setValue and patchValue here

    0 讨论(0)
  • 2020-12-17 09:15

    Probably the error appears because this.flightChoice.DestinationId === undefined and you try to set undefined to the Destination field on the form.

    Check if api is correctly downloading data to this.flightChoice.

    0 讨论(0)
提交回复
热议问题