Issue: Angular is indicating that the 'feedbackFormDirective' member is implicitly assigned with type 'any'

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>       
                                                             ~~~~~~~~...

Answer №1

To prevent any implicit type errors, it is recommended to specify a type for your form explicitly.

import {NgForm} from '@angular/forms';

...

@ViewChild('fform') feedbackFormDirective: NgForm;


Answer №2

Have you ever attempted utilizing the ? operator?

<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>

Given that you are accessing a specific formControl by referencing its name,

for instance:

form?.get('noneExistentControl').value

Angular aims to prevent accessing a possible null object, which is why employing the ? Optional chaining operator securely validates whether a value is invalid or valid.

Optional chaining

Answer №3

When the error message 'object is possibly null' appears, you can resolve it by adding a '?' after "feedbackForm.get('lastname')" and updating the code snippet as shown below:

<mat-error *ngIf="feedbackForm.get('lastname')?.hasError('required') && 
feedbackForm.get('lastname')?.touched">Last Name is required</mat-error>

Happy coding!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular application experiencing issues with loading React web component: encountering error when attempting to search for 'adoptedCallback' using 'in' operator with undefined value

I recently created a basic web component using React import React from "react"; import ReactDOM from "react-dom/client"; import reactToWebComponent from 'react-to-webcomponent'; function Test() { return ( <h1> He ...

When I make a post request, I receive a response in the form of an HTTPS link, but it is not redirected to

I'm making a post request and receiving the response as follows: " [Symbol(Response internals)]: {url: 'https://login.somenewloginpage'}" My intention is to open a new page using that URL, but unfortunately it does not redirect t ...

Can you please explain the significance of the code "!!~this.roles.indexOf('*')" within the MEAN.io framework?

One particular line of code can be found in the startup file for the MEAN framework. if (!!~this.roles.indexOf('*')) { This specific line is located within the shouldRender function of the menus.client.service.js file, which resides in the publ ...

how can a select dropdown be dynamically displayed based on the previous selection?

If the first dropdown is set to "Professor" I want to display a second dropdown, but if it is set to "Student" then I do not want to display the second dropdown. function checkPrivilege() { var privilege = document.getElementById("permisija5").value; ...

Numerous CSS/JS Dropdown Menus

I am seeking the ability to implement a dropdown through CSS in various locations within my HTML prototype. This implies that I require the capability to position multiple dropdowns anywhere on the page. Currently, I utilize this method to generate a sing ...

Unexpected triggering of second fail in Jquery Deferreds

Currently, I have a sequencing function that involves two REST steps - step 1 and step 2. The way I am currently handling this is by calling step1 with fail and then handlers, followed by step2 with its own fail and then handler. self.step1() .fail(se ...

Incorporate Font Awesome icons throughout your Angular8 application for added visual appeal

I'm currently working on a large Angular application that utilizes lazy loading modules. Throughout various components in different modules, I make use of icons from Font Awesome individually. Here is an example: In component.ts: import { faChevronD ...

Encountering module error 'internal/fs' after updating to Node 7

We have encountered some challenges after attempting to update our build server to node v7.0.0. Specifically, the application build task fails at the "bower_concat" step with the following error message: Loading "bower-concat.js" tasks...ERROR Error: Cann ...

Ways to verify if an email has been viewed through the client-side perspective

How can I determine if an email has been read on the client side using PHP? I need to verify if emails sent by me have been opened by recipients on their end. Additionally, I would like to extract the following details from the client's machine: 1. ...

Is it advisable to compress my API response in PHP?

At this stage, I find myself needing to generate extensive reports in order to gain a better understanding of the data at hand. To do so, I must retrieve one of my tables which contains around 50 parameters and 40,000 rows. While fetching the data via API ...

Utilizing the 'container' property in a React.js React-Bootstrap modal

How can I open a modal within a designated container using the native property "container"? Whenever I specify the class name of the container element, I encounter an error TypeError: Cannot use 'in' operator to search for 'current' in ...

Dealing with multiple jQuery ajax requests - strategies for managing them

Whenever I click the button quickly while there is jQuery Ajax loading, it seems to get stuck. How can I manage multiple requests being fired at the same time? What is the solution for the following: Cancel/abort all previous requests and only handle th ...

Dealing with errors in Next.js api: Best practices

When it comes to organizing code in Next.js api handlers, what is the most effective practice? In a video I watched, the presenter suggested placing all REST routes in two specific files: pages/api/users/index.ts would manage operations that do not requ ...

Implementing ngFor to Iterate Through a JSON Object in Angular 6

Iterate through the object list retrieved from a JSON object Here is the JSON object that I have fetched: { "0": { "0": null, "1": "Consolidated Statements of Changes in Stockholders\u2019 Deficit", "2": null, "3": "", "4": "" ...

Exploring the implementation of if/else statements in Sass/HTML

I need assistance with customizing the appearance of a save button on my form. The button is currently disabled and appears in blue color, but I would like it to change to a different color until all fields within the form are completed. Even though it c ...

What steps should I take with my Android PWA manifest and service workers?

I created a web application that I want to prompt Android users to download when they visit. To build my service workers and manifest, I utilized PWA Builder which can be found at Now that I have the manifest file ready, should I simply upload it to the r ...

Discovering which chip has wrapped to the next line in Material UI Autocomplete can be found by closely inspect

Currently, I am working with a Material UI autocomplete feature that functions as follows: My goal is to determine when the fourth chip wraps to the next line within the autocomplete so that I can proceed with additional calculations. Is there a method in ...

Leverage ng2-charts along with a loading component during the AfterViewInit lifecycle hook

Currently, I am working on a web page that contains various charts. My focus right now is on developing a simple loader as shown below: <div *ngIf="loading === true; else elseBlock" class="container"> <div class="grid-pulse la-3x"> </di ...

What are your thoughts on combining a JSON object with HTML?

When using ASP.NET MVC, it is possible to return a JSONResult. return JSON(new { View = RenderViewAsString("MyView", model), wasSuccessful = true}) This approach combines HTML and data in a single JSON object. The goal is to utilize strongly typed HtmlHe ...

Create a jQuery script that generates clickable links when a user is mentioned in the

Hey there, I've been incorporating this fantastic plugin created by Hawkee into my project. It functions similarly to Twitter, allowing users to @mention others. However, I'm encountering issues with the output when using the following method: u ...