Reputation: 2647
In my Angular-12, I have this code:
editForm: FormGroup;
onSubmit() {
// Stop processing form submission if form data is invalid //
if (this.editForm.invalid) {
return;
}
// processing form submission data to server //
const formData = new FormData();
formData.append('heading', this.editForm.get('heading').value);
formData.append('title', this.editForm.get('title').value);
formData.append('image', this.editForm.get('image').value);
formData.append('description', this.editForm.get('description').value);
formData.append('id', this.editForm.get('id').value);
this.http.post(this.serverUrl + 'updateAbout', formData).subscribe((res: any) => {
this.router.navigate(['admin/about']).then(() => this.showToasterSuccess(res.message));
},
error => this.router.navigate(['admin/about']).then(() => this.showToasterError(error[0].message))
);
}
We got this error:
Object is possibly 'null'.ts(2531)
and this is highlighted:
formData.append('heading', this.editForm.get('heading').value);
I applied some of the similar solutions in stackoverflow, but none is working.
For instance, in tsconfig.json, I added "strictNullChecks": true to:
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": true,
"strictNullChecks": true
}
But the problem is still not resolved.
How do I get it sorted out?
Thanks
Upvotes: 0
Views: 1238
Reputation: 93
You have to instantiate the formGroup as shown below
ngOnInit(): void {
this.editForm = new FormGroup({
heading: new FormControl('heading'),
title: new FormControl('title'),
image: new FormControl('image'),
description: new FormControl('description'),
id: new FormControl('id'),
});
}
In onSubmit :
onSubmit() {
// Stop processing form submission if form data is invalid //
if (this.editForm.invalid) {
return;
}
// processing form submission data to server //
const formData = new FormData();
formData.append('heading', this.editForm.value.heading);
console.log(this.editForm.value.heading);
}
regards,
Upvotes: 0
Reputation: 19764
formData.append('heading', this.editForm.get('heading').value);
^
Angular cannot be sure that a form control exists with a name heading
, which is why the get
method returns an AbstractControl | null
. If you're sure that you're not making a typo with 'heading'
and you're sure that the result will be non-null, you can use a non-null assertion operator.
formData.append('heading', this.editForm.get('heading')!.value);
Upvotes: 2