I am encountering an error in my project while using Angular version 12. Despite extensive research, I have been unable to find a solution.
Here is my .ts file:
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Feedback, ContactType } from '../shared/feedback';
...
export class ContactComponent implements OnInit {
feedbackForm!: FormGroup;
feedback!: Feedback;
contactType = ContactType;
@ViewChild('fform') feedbackFormDirective;
constructor(private fb: FormBuilder) {
this.createForm();
}
ngOnInit(): void {
}
onSubmit() {
this.feedback = this.feedbackForm.value;
console.log(this.feedback);
this.feedbackForm.reset({
firstname: '',
lastname: '',
telnum: '',
email: '',
agree: false,
contacttype: 'None',
message: '',
});
this.feedbackFormDirective.resetForm();
}
}
Now moving on to my .html file:
...
<form novalidate [formGroup]="feedbackForm" #fform="ngForm" (ngSubmit)="onSubmit()">
<p>
<mat-form-field class="half-width">
<input matInput formControlName="firstname" placeholder="First Name" type="text" required>
<mat-error *ngIf="feedbackForm.get('firstname').hasError('required') && feedbackForm.get('firstname').touched">First name is required</mat-error>
</mat-form-field>
<mat-form-field class="half-width">
<input matInput formControlName="lastname" placeholder="Last Name" type="text" required>
<mat-error *ngIf="feedbackForm.get('lastname').hasError('required') && feedbackForm.get('lastname').touched">Last name is required</mat-error>
</mat-form-field>
</p>
<p>
<mat-form-field class="half-width">
<input matInput formControlName="telnum" placeholder="Tel. Number" type="tel" required>
<mat-error *ngIf="feedbackForm.get('telnum').hasError('required') && feedbackForm.get('telnum').touched">Tel. number is required</mat-error>
</mat-form-field>
<mat-form-field class="half-width">
<input matInput formControlName="email" placeholder="Email" type="email" required>
<mat-error *ngIf="feedbackForm.get('email').hasError('required') && feedbackForm.get('email').touched">Email ID is required</mat-error>
</mat-form-field>
</p>
<table class="form-size">
<td>
<mat-slide-toggle formControlName="agree">May we contact you?</mat-slide-toggle>
</td>
<td>
<mat-select placeholder="How?" formControlName="contacttype">
<mat-option *ngFor="let ctype of contactType" [value]="ctype">
{{ ctype }}
</mat-option>
</mat-select>
</td>
</table>
<p>
<mat-form-field class="full-width">
<textarea matInput formControlName="message" placeholder="Your Feedback" rows=12></textarea>
</mat-form-field>
</p>
<button type="submit" mat-button class="background-primary text-floral-white" [disabled]="feedbackForm.invalid">Submit</button>
</form>
</div></div>
The error that has surfaced reads as follows:
Object is possibly 'null'.
48 <mat-error *ngIf="feedbackForm.get('firstname').hasError('required') && feedbackForm.get('firstname').touched">First name is required</mat-error>
~~~~~~~~...