The object in an Angular 11 REACTIVE FORM may be null

I am looking to incorporate a reactive form validation system in my application, and I want to display error messages based on the specific error. However, I am encountering an error that says: object is possibly 'null'.

signup.component.html

<form [formGroup]="form">
        <div class="form-group">
            <label for="username">Username</label>
            <input 
            formControlName="username"
            class="form-control"
            id="username"
            type="text">
        <div class="alert alert-danger" *ngIf="username?.touched && username?.invalid">
                <div *ngIf="username.errors.required">username is required !</div>
                <div *ngIf="this.form.controls['username'].errors?.minlength">username must have at least {{ username.errors.minlength.requiredLength }} characters</div>
        </div>
        </div>
</form>

signup.component.ts

form = new FormGroup({
    username: new FormControl('',[
      Validators.required,
      Validators.minLength(3),
    ]),
    
  })

  get username(){
    return this.form.get('username')
  }

Answer №1

I have a feeling that this sentence could use a question mark.

<div *ngIf="username?.errors?.required">Username is required!</div>

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 HTTP Requests with Observables

In order to enhance the security of my Angular web application, I am currently in the process of developing a TypeScript method that will validate a JWT token on the server using an HTTP call. It is imperative for me that this method returns a boolean val ...

Leveraging Google Analytics with Angular 4 and beyond

Having trouble integrating Google Analytics with Angular 4? Can't seem to find the @type for ga.js in ts? Here's a quick fix that I implemented in every component: declare let ga: any; How did I solve it, you ask? I created a function to dyna ...

The 'XXX' property is not found in 'YYY' type but is necessary in 'ZZZ' type

I'm struggling with setting up class properties in TypeScript. Here is the TypeScript code that I am working on: export class myClass { a: number; b: number; public getCopy(anotherClass: myClass): myClass { return { a: anotherClass.a, ...

Is there a way to tidy up the surplus space between the variable and dot in Angular?

I'm experiencing an issue with spacing in the rendered HTML of my Angular template that includes a condition block with ng-container. How can I resolve this issue? This is the template section causing the problem: <span&g ...

Encountering a ReferrenceError when utilizing jQuery with TypeScript

After transitioning from using JavaScript to TypeScript, I found myself reluctant to abandon jQuery. In my search for guidance on how to integrate the two, I came across several informative websites. Working with Visual Studio 2012, here is my initial atte ...

The color attribute for the ion-button element is not functioning properly on Android devices in

In my app, it functions correctly when running on iOS, but encounters issues when running on Android. The problem lies in the color attribute not working on buttons and other elements on Android. Removing the attribute makes them visible, but the desired s ...

Binding iframes in Angular 6

Is there a way to display iframe code stored in a variable within a div? Here's the HTML code: <div class="top-image" [innerHTML]="yt"></div> And here's the TypeScript code: yt = '<iframe class="w-100" src="https://www.you ...

Potential solution for communication issue between Angular CLI and Flask due to cross-origin error

Initially, the user id and password are submitted from the UI (angular) to Flask: public send_login(user){ console.log(user) return this.http.post(this.apiURL+'/login',JSON.stringify(user),this.httpOptions) .pip ...

TypeScript Error 2304: Element 'div' is nowhere to be found - CRA TypeScript Template

I'm experiencing a problem in VSCode while working on the default create-react-app my-app --template typescript project. It seems to not recognize any HTML elements, as I keep getting the error cannot find name xxx, where 'xxx' represents th ...

Using checkboxes to filter a list within a ReactiveForm can result in a rendering issue

I have implemented a dynamic form that contains both regular input fields and checkboxes organized in a list. There is also an input field provided to filter the checkbox list. Surprisingly, I found out that when using the dot (.) character in the search f ...

Issues with Webpack and TypeScript CommonsChunkPlugin functionality not functioning as expected

Despite following various tutorials on setting up CommonsChunkPlugin, I am unable to get it to work. I have also gone through the existing posts related to this issue without any success. In my project, I have three TypeScript files that require the same ...

What is the method to incorporate @angular/fire into an Nx Workspace for an Angular project?

Incorporating @angular/fire into my Nx workspace for my Angular application is my current goal. Despite my efforts to adhere to best practices, I have not found any guidance in the official documentation on how to incorporate this library into the wor ...

Enhancing Angular routing with multiple parameters

When I am using either routerLink or router.navigate, I face an issue where I have an array containing multiple values that need to be serialized into ?id=val1&id=val2. However, the problem arises when trying to set an optional route parameter as an ar ...

What causes the issue of observable subscription displaying incorrect data for a brief period during page refresh within a lifecycle hook?

I am facing an issue with subscribing to an observable within a component lifecycle hook. While the content is correctly displayed in the template, making changes to the DOM through a component method results in a strange behavior upon page refresh. Initia ...

The function is failing to return the expected value received from the observable subscription

I am attempting to verify the existence of a user in an Angular's in-memory API by validating their username. The function checkUsernameExists(username) is supposed to return an Observable<boolean> based on whether the API responds with undefine ...

a guide to caching a TypeScript computed property

I have implemented a TypeScript getter memoization approach using a decorator and the memoizee package from npm. Here's how it looks: import { memoize } from '@app/decorators/memoize' export class MyComponent { @memoize() private stat ...

In Angular, upon submitting the form, redirect to a separate component and display a message indicating the successful

I am facing an issue with a component that sends data to a service in order to save it in the database. Following this, I want to redirect or navigate to a different component and display a success message there. While I have implemented this functionality ...

BrowserRouter - The type '{ children: Element; }' is not compatible with the type 'IntrinsicAttributes', as they do not share any properties in common

After upgrading to React version 18, I encountered a type error with the BrowserRouter component. Despite trying various approaches, I am unable to pinpoint the root of the problem. Here is the error that pops up during debugging: Overload 1 of 2, &a ...

When utilizing WPF WebBrowser with a local Angular 8 website, the window.external feature works flawlessly. However, complications arise when

Apologies for any formatting issues, this is my first post. I have been working on updating a legacy app with a new UI. This serves as a proof of concept to demonstrate our ability to create a thin client and host our project online. In my WPF window (.NE ...

Step-by-step tutorial on how to enable app logout functionality using Node.js and Okta

I have created a web app using Okta with OIDC and Node Express for user authentication. I want users to be able to log out of my app without logging out of the company Okta, which is used for multiple websites. Okta recommends this approach on their websit ...