The 'formGroup' property cannot be bound as it is not recognized as a valid property of 'form' in Angular 7

I tried implementing a login feature using web API with Angular 7, but encountered an error when using

<form [formGroup]="loginForm" (submit)="loginFormSubmit()">
. What could be causing this issue?

https://i.sstatic.net/3M2a5.jpg

login.component.html

<form [formGroup]="loginForm" (submit)="loginFormSubmit()">              
                <h2 class="text-center red heading text-heading">LOGIN</h2>
                <div class="form-group custom-input">
                    <div>
                        <span style="color: #D56161;" class="lblMessage"></span>
                    </div><br>
                    <div class="input-group">
                        <div class="input-group-prepend">
                        <span class="input-group-text">
                            <i class="fa fa-user"></i>
                        </span>
                    </div>
                        <input class="form-control" data-val="true" data-val-required="required" formControlName="userId" placeholder="Username" type="text" value="">
                    <small class="text-danger" *ngIf="loginForm.form-control.userId.invalid && (loginFormSubmitted  || loginForm.controls.userId.touched)">Required</small>
                    </div>
                    <div style="text-align:left">
                        <span class="field-validation-valid" data-valmsg-for="UserName" data-valmsg-replace="true" style="color:#D56161;"></span>
                    </div>
                </div>
                <div class="form-group">
                    <div class="input-group">
                    <div class="input-group-prepend">
                        <span class="input-group-text">
                            <i class="fa fa-lock"></i>
                        </span>
                    </div>
                        <input class="form-control" data-val="true" data-val-required="required" id="Password" formControlName="Password" placeholder="Password" type="password">
                        <small class="text-danger" *ngIf="loginForm.controls.password.invalid && (loginFormSubmitted || loginForm.controls.password.invalid)">Required</small>
                    </div>
                    <div style="text-align:left">
                        <span class="field-validation-valid" data-valmsg-for="Password" data-valmsg-replace="true" style="color:#D56161;"></span>
                    </div>
                </div>
                <div class="form-group">
                    <button type="submit" class="btn btn-block btn-primary button login" [disabled]="loginFormSubmitted">LOGIN <i class="fa fa-arrow-right"></i></button>
                </div>
                <hr>
                <div class="row">
                    <div class="col-lg-12">
                        <a class="float-left" href="/Admin/ForgotPassword">Forgot Password?</a>
                        <a class="float-right" href="">Back to Website</a>
                    </div>
                </div>
            </form>

login.component.ts

import { Component } from '@angular/core';
import { ApiService } from '../../../../services/api/api.service';
import { Observable } from 'rxjs';

@Component({
    selector: 'app-login',
    templateUrl: './login.component.html'
})

export class loginComponent{

    users$: object;

    constructor(private data: ApiService){
    }

    ngOnInit(){

    }

    loginFormSubmit(){
        alert('login alert');
    }

}

What steps can I take to address this issue?

Appreciate any guidance!

Answer №1

To start, you need to establish a formGroup in the login.ts file.

Begin by importing the Forms Module and Reactive forms module into the module where the login component is declared. This step should resemble the following:

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';

@NgModule({
  declarations: [
    loginComponent
  ],
  imports: [
    BrowserModule,
    ReactiveFormsModule,

  ],

  bootstrap: [AppComponent]
})
export class AppModule { }

Proceed to the login.ts file and create a form group. Here is an example using the form builder method, but other methods can also be utilized. For more detailed guidance, refer to the link provided below: angular reactive forms

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, FormBuilder } from '@angular/forms';

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

@Component({
  // add your meta data here
})
export class loginComponent implements OnInit {

  constructor(fb:FormBuilder) { }

  ngOnInit() {
  }

  private loginForm = this.fb.group({
    userId: ['',],
    // add other form controls within the group

  });

}

Answer №2

If you encounter an error in the debugger stating that formGroup is not defined in pure HTML, don't worry - you can resolve this by importing ReactiveFormsModule from the @angular/forms package into your project. The [formGroup] directive is provided and exported by ReactiveFormsModule.

Since the [formGroup] directive is exported by ReactiveFormsModule, you can use it in any component within a Module that imports ReactiveFormsModule.

The formGroup directive includes an @Input property called formGroup. By binding the instance of your formGroup in the TypeScript file to this @Input property inside the formGroup directive, you are properly connecting the two.

It's important to note that the formGroup directive from ReactiveFormsModule acts as a child for your component. To communicate with a child component in Angular, utilize property binding like you are doing here.

This pattern of property binding and event binding is commonly used throughout the Angular framework, making it essential to understand for working effectively with Angular 2+.

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

Guide to setting a dynamic value for an input List property in Angular

How can I render multiple dropdowns in Angular based on the response from an API? Currently, when I retrieve data from the API, I am seeing the same information displayed in both dropdown controls. Is there a way to assign dynamic values to the "list" prop ...

Refresh the display after adding an item to an array in Angular

Currently, I am facing an issue with updating the view based on adding an item to an array of objects through a click handler. While the item is successfully pushed into the array, it does not reflect in the view. I am wondering if placing the method withi ...

Combining declarations with a personalized interface using TypeScript

My goal is to enhance the express.Request type by adding a user property so that req.user will be of my custom IUser type. After learning about declaration merging, I decided to create a custom.d.ts file. declare namespace Express { export interface ...

Separate HTTP responses into multiple Observables

I need assistance in splitting a HTTP response into different Variables/Observables. The returned data is in JSON format: [ { "status": [ { "id": 1, "value": "active"}, { "id": 2, "value": "inactive"} ] }, { "type": [ ...

Is there a way to programmatically activate the iOS unavailable screen?

Is there a way to programmatically simulate the iPhone unavailable screen after entering the wrong password multiple times, with a specific time delay? I am searching for an API that can remotely lock my iPhone screen so that it cannot be unlocked by me. ...

deleting the existing marker before placing a new marker on the Mapbox

Upon the map loading with GeoJson data, I have implemented code to display markers at specified locations. It works flawlessly, but I am seeking a way to remove previous markers when new ones are added. What adjustments should be made for this desired func ...

Issue with displaying Angular index.html page post-build

My Angular application runs smoothly on ng serve, but after building and uploading with ng build --prod, the index.html file fails to open. I've tried using various base href configurations like <base href="#">, <base href="/& ...

React App PWA ERROR: Service worker not registered to control the page and start_url

I am encountering an issue while building a progressive web app using Create React App. Lighthouse benchmarking results in an error, indicating that my PWA is not installable. Surprisingly, I face the same problem even when utilizing the official PWA templ ...

Issue with Component Generation in Angular CLI version 6.0.0

Upon updating Angular CLI to version 6.0.0 and creating a new app using ng new my-app, I encountered an error when trying to generate a component with ng g c my-component: An NgModule was not found. Please consider using the skip-import option to bypass i ...

What is the process for obtaining the result and storing it in an array using M

Recently, I just started exploring angular and ventured into using mongoose with mongodb. Within my application, I require a list of driver names in the form of a string array. However, instead of receiving a simple array of names, I am getting an array o ...

Exploring the world of Ionic and Angular on Coursera

I've been following a Coursera tutorial, but I've encountered an error. Although I have the code provided by the teacher, it's not working as expected. Unfortunately, I am unsure of what additional code to include since everything seems to ...

The API call retrieval encountered an issue due to CORS, as the nginx configuration settings were not correctly

Greetings and thank you for your valuable time I am currently running a dotnet core web api application on port 6000, alongside an angular application. I have set up nginx to reverse proxy to the dotnet core application, and to the angular application ...

Angular 2 - Directive fails to work if not properly imported into its module

Trying to use a directive across multiple modules in Angular can be tricky. If you declare it in a shared module and import that module into other modules, you might encounter errors. It seems like the directive only works when declared directly within the ...

How to Incorporate and Utilize Untyped Leaflet JavaScript Plugin with TypeScript 2 in Angular 2 Application

I have successfully integrated the LeafletJS library into my Angular 2 application by including the type definition (leaflet.d.ts) and the leaflet node module. However, I am facing an issue while trying to import a plugin for the Leaflet library called "le ...

Exploring JS Pattern Matching across Two Distinct Data Sources

In my database, I have two tables (and more can be added in the future) with rows structured like this: <table> <tr> <th>name</th> <th>salary</th> </tr> <tr> <td>a</td> &l ...

Incorporating SVG graphics within a SharePoint web part

I am in the process of developing a webpart for SharePoint using the SharePoint Framework, TypeScript, and ReactJS. I have encountered an issue while trying to incorporate an svg image into my webpart code, resulting in build errors. Initially, I used the ...

What is the reason behind Typescript errors vanishing after including onchange in the code?

When using VSCode with appropriate settings enabled, the error would be displayed in the following .html file: <!DOCTYPE html> <html> <body> <div> <select> </select> </div> <script&g ...

There was an issue retrieving the metadata for the bootstrap package using the git+ssh protocol

While attempting to install angular devkit and other dependencies using npm install, I encountered the following error message: Could not retrieve metadata for bootstrap@git+ssh://example@example.com/gios/Web-Standards-Bootstrap.git#05a343dddce91dd157702 ...

Why am I encountering this issue? The "map" property does not appear to be available for the type "Observable<boolean>"

I have been working on an Angular project where I am utilizing an AuthGuard class to prevent unauthorized access to protected pages. Despite following an online course, I encountered the following issue: import { CanActivate, ActivatedRouteSnapshot, Router ...

In Javascript, determine the root cause of a boolean expression failing by logging the culprit

Within my JavaScript code, I have a complex predicate that comprises of multiple tests chained together against a value. I am looking for a way to log the specific location in the expression where it fails, if it does fail. Similar to how testing librarie ...