Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Angular getting "TS2531: Object is possibly 'null' on object values

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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')
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading