I am new to reactive forms, I am trying to assign the form values (all string inputs) from my reactive form to a variable which has type of object of strings. I get the following error
"Type 'Partial<{ taskName: string | null; taskDate: string | null; taskPriority: string | null; }>' is not assignable to type 'ToDoDetailType'. Types of property 'taskName' are incompatible. Type 'string | null | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type 'string'."
export class ToDoMakerComponent implements OnInit{
ngOnInit(): void {
}
toDoForm = new FormGroup({
taskName : new FormControl<string>('',[Validators.required]),
taskDate : new FormControl('',[Validators.required]),
taskPriority : new FormControl('',[Validators.required])
})
toDoDetail:ToDoDetailType | undefined;
onSubmit(){
console.log(this.toDoForm.value);
this.toDoDetail = this.toDoForm.value //error raising line
}
}
export interface ToDoDetailType{
taskName: string,
taskDate: string,
taskPriority: string
}
You have 2 problems here :
FormControl
creates a nullable control by default but you can't create a nonNullable
with a validator. The common alternative is to use the FormBuilder.nonNullable
.todoForm.value
returns a Partial<ToDoDetailType >
because any disabled FormControl
won't be included in the value. If you're sure non control will be disabled the common alternative is getRawValue()
.Which gives us :
constructor(private fb:FormBuilder) {}
toDoForm = this.fb.nonNullable.group({ // create a non nullable group
taskName: ['', [Validators.required]],
taskDate: ['', [Validators.required]],
taskPriority: ['', [Validators.required]],
});
onSubmit() {
this.toDoDetail = this.toDoForm.getRawValue(); // Not a partial
}