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

Another return payload failing to retrieve the return value

I'm currently facing an issue where a function that should return a value is not being passed on to another function. Below is the code snippet in question: public _getProfileToUpdate() { return { corporateId: this.storeService.setStoreData().p ...

Is there a way to determine if a browser's Storage object is localStorage or sessionStorage in order to effectively handle static and dynamic secret keys within a client?

I have developed a customizable storage service where an example is getExpirableStorage(getSecureStorage(getLocalStorage() | getSessionStorage())) in typescript/javascript. When implementing getSecureStorage, I used a static cipher key to encrypt every ke ...

Observables waiting inside one another

I've encountered an issue where I need to return an observable and at times, within that observable, I require a value from another observable. To simplify my problem, let's consider the following code snippet: public dummyStream(): Observabl ...

Tips on customizing the Nuxt Route Middleware using Typescript

I am working on creating a route middleware in TypeScript that will validate the request.meta.auth field from the request object. I want to ensure this field has autocomplete options of 'user' and 'guest': export default defineNuxtRoute ...

What is the reason behind Angular 2's choice to implement the .ts file extension?

What is the significance of using the .ts file extension in Angular 2? ...

Attempting to utilize a namespace-style import for calling or constructing purposes will result in a runtime failure

Using TypeScript 2.7.2 and VSCode version 1.21 with @types/express, I encountered an issue where in certain cases VSCode would report errors like: A namespace-style import cannot be called or constructed, and will cause a failure at runtime. Interestingly ...

Pull information from API and populate a dropdown menu in an Angular material select input

I am facing an issue with displaying data from an API in a mat select input field. I have tried to iterate over the data using a for loop but it is not working as expected. Can someone help me figure out how to properly populate the mat select input with d ...

I'm interested in developing a feature that monitors a specific attribute and triggers a function once that attribute hits the value of 100

I am working on a function that will refresh the view once the percentage changes reaches 100: The value is stored in this variable: this.uploadPercent = task.percentageChanges(); This is the function I plan to implement : refreshView(){ Once this.uplo ...

Guide on positioning a span element to the left using the margin auto property in CSS for Angular 4

Having trouble with moving numbers highlighted to the left with names in CSS. I've tried using flex direction and margin auto but can't achieve the desired result. Here is my HTML code: <section class="favorites"> <div class="category" ...

A different approach to fixing the error "Uncaught (in promise) TypeError: fs.writeFile is not a function" in TensorFlow.js when running on Chrome

I've been attempting to export a variable in the TensorFlow posenet model while it's running in the Chrome browser using the code snippet below. After going through various discussions, I discovered that exporting a variable with fswritefile in t ...

When running the command ng build --prod, it seems that the module for class X cannot be determined. To resolve this issue, make sure to include

I'm encountering an issue while trying to develop my Angular 5 application. The error message reads: Cannot determine the module for class ThreadListTabsComponent in /home/brightwater/Differ/src/app/thread-lists/thread-lists.component.ts! Add T ...

Currying disrupts the inference of argument types as the argument list is divided in half, leading to confusion

One of my favorite functions transforms an object into a select option with ease. It's written like this: type OptionValue = string; type OptionLabel = string; export type Option<V extends OptionValue = OptionValue, L extends OptionLabel = OptionL ...

Creating a dynamic linear gradient background color using Angular 2 binding

Using static values works perfectly <div style="background: linear-gradient(to right, #0000FF 0%, #0000FF 50%, #FFA500 50%, #FFA500 100%);"></div> in my TypeScript file. this.blueColor = '#0000FF'; this.orangColor = '#FFA500&a ...

Error: JSON parsing error - Unexpected token at the start of the JSON data when using JSON.parse() function

Backend code router.route('http://localhost:5007/api/media') .post(mediaCtrl.saveMedia) async saveMedia(req, res) { let file = req.files.file let ext = req.body.extension let path = req.body.path if(_.isNull(file) || _.isEmp ...

It appears that the blob data is not being received in the message sent from the websocket server to my Angular 2 Observable

Having trouble converting some html/javascript to Angular 2 and encountering an issue with blob data not being received in messages from the websocket host to the Angular 2 Observable. Text messages are being sent successfully from the websocket host, but ...

Using Angular to display asynchronous data with ngIf and observables

In cases where the data is not ready, I prefer to display a loader without sending multiple requests. To achieve this, I utilize the as operator for request reuse. <div class="loading-overlay" *ngIf="this.indicatorService.loadingIndicators[this?.indic ...

Troubleshooting Vue Unit Tests: Issue with Setting Input Values

I am currently utilizing Vue with typescript and making an effort to perform a unit test on the input value for a login page. The issue lies in the fact that after setting the input value, it does not return as expected – instead, it comes back empty ("" ...

Content from PHP's unlink() function continues to persistently display

I run an Angular front end along with a PHP back end for my website. I utilize PHP's unlink function to remove specific images from Angular's assets folder: $fileToDelete = "../src/assets/images/".$name; unlink($fileToDelete) or die("Error delet ...

Maximizing Performance: Enhancing Nested For Loops in Angular with Typescript

Is there a way to optimize the iteration and comparisons in my nested loop? I'm looking to improve my logic by utilizing map, reduce, and filter to reduce the number of lines of code and loops. How can I achieve this? fill() { this.rolesPermiAdd = ...

Utilizing symbols as a keyof type: A simple guide

Let's consider the following: type Bar = keyof Collection<string> In this scenario, Bar denotes the type of keys present in the Collection object, such as insert or remove: const x: Bar = 'insert'; ✅ But wait, the Collection also c ...