Issue
I'm trying to put form controls values in an object to pass in an onSubmit method but when I assign the values of the form controls to the object I get this error
TS2531: Object is possibly 'null'.
when hovering the filters object properties in the onSubmit() method
my code:
export class SearchBarComponent implements OnInit {
filtersForm! : FormGroup
constructor(private jobService : JobsService) { }
@Output() OutputFilter = new EventEmitter<string>()
filters! : {
city: string,
level: string
}
ngOnInit(): void {
this.filtersForm = new FormGroup({
city: new FormControl('Italy, Roma'),
level: new FormControl(),
})
}
onSubmit(): void{
this.filters = {
city : this.filtersForm.get('city').value,
level : this.filtersForm.get('level').value
}
this.OutputFilter.emit(this.filters)
console.log('Submitted')
}
}
what am I doing wrong here? I tried adding ! and ? operators to everything but I can't figure out what is the problem
Solution
From Angular DOC
On any FormGroup, it is possible to disable controls. Any disabled control will not appear in the group's value.
More specifically, the type of this.filtersForm.get('city').value
is string|undefined
, and TypeScript will enforce that you handle the possibly undefined value (if you have strictNullChecks enabled).
If you want to access the value including disabled controls, and thus bypass possible undefined fields, you can use this.filtersForm.getRawValue()
Try this:
onSubmit(): void{
const {city, level} = this.filtersForm.getRawValue();
this.filters = {
city,
level
}
this.OutputFilter.emit(this.filters)
console.log('Submitted')
}
Answered By - Chellappan வ
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.