Guide to activating a button with reactive forms in angular 2

I am facing an issue where I have an input field and a button. The button should be enabled when the field is not empty. However, even though I am already passing an input value, the button is not being enabled as expected. It only gets enabled when I actually type something in the input field. Does anyone have any advice on how to resolve this? Below is the code snippet:

export class SignupFormComponent implements OnInit {
  userForm: FormGroup;
  submitted: boolean;
  hello = "hello world";

  ngOnInit() {
    this.userForm = new FormGroup({
      firstName: new FormControl('',[<any>Validators.required, <any>Validators.minLength(5)])
    });
  }

  onSubmit({ value, valid }: { value: userForm, valid: boolean }) {
    this.submitted = true;
    console.log(value,valid);
  }
}

Here is my HTML code:

<form [formGroup]="userForm" (ngSubmit)="onSubmit(userForm)" validate>
  <div class="form-group">
    <label>First Name</label>
    <input type="text" class="form-control" formControlName="firstName" [value]="hello">
  </div>
  <button type="submit"  class="btn btn-primary" [disabled]="userForm.invalid">Submit </button>
</form>

Answer №1

To properly set up your reactive form, it is important to remove the [value]="hello" from the input field and instead include it in the

new FormControl(value, [validators], [asyncValidators])
.

Here's an example of how you can do this:

ngOnInit() {
  this.userForm = new FormGroup({
    firstName: new FormControl(this.hello, [<any>Validators.required, <any>Validators.minLength(5)])
  });
}

Answer №2

To make things simpler, you can utilize reactive forms in the following manner:

  • step1: Start by importing ReactiveForm, FormBuilder, Validators
  • step2: Create a FormGroup object and inject form builder into the constructor
  • step3: Initialize your form group
  • step4: Implement the reactive form just like before but with some modifications

Code:

export class RegistrationComponent implements OnInit {
  userForm: FormGroup;
  firstName: string;

  constructor(private _formBuilder:FormBuilder){}

  ngOnInit() {
    this.userForm = this._formBuilder.group({
      'firstName': ['',[Validators.required,Validators.minLength(5)]]
    });
  }

  onSubmit() {
    console.log(this.firstName);
  }
}

HTML:

<form [formGroup]="userForm" (ngSubmit)="onSubmit()" name="userForm">
      <div class="form-group">
        <label>First Name</label>
        <input type="text" [(ngModel)]="firstName" class="form-control" formControlName="firstName">
        <p *ngIf="userForm.controls.firstName.invalid && (userForm.controls.firstName.dirty || userForm.controls.firstName.touched)"> Error message </p>
      </div>
      <button type="submit"  class="btn btn-primary" [disabled]="userForm.invalid">Submit </button>
    </form>

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

Fetching User Details Including Cart Content Upon User Login

After successfully creating my e-commerce application, I have managed to implement API registration and login functionalities which are working perfectly in terms of requesting and receiving responses. Additionally, I have integrated APIs for various produ ...

Having trouble updating an NPM dependency within package.json that is already installed as a dependency

I encountered an error message while trying to import mongoose with TypeScript node_modules/mongoose/node_modules/mongodb/mongodb.d.ts:3309:5 - error TS2416: Property 'end' in type 'GridFSBucketWriteStream' is not assignable to the same ...

Issues with mat-input functionality within a mat-table in Angular 8

I'm encountering an issue with my mat-table. The input field within the table is not functioning properly. All rows are sharing the same input field, so when I type text into the box, it appears in all rows. Here is my code: <ng-container matColum ...

Error message: The database query function is encountering an issue where the property 'relation.referencedTable' is undefined and cannot be accessed

Currently, I am working with two schemas named products.ts and category.ts. The relationship between these files is defined as one-to-many. In the products.ts file: import { pgTable, timestamp, uuid, varchar } from "drizzle-orm/pg-core"; import ...

Retrieve the interface property following the execution of the HTTP GET service

Having trouble accessing the array properties from my JSON file using the http get service. The goal is to display the Widget array on the web. service.ts: import { Http, Response, Headers } from '@angular/http'; import { Observable } from &apo ...

What is the timing for the execution of top-level non-export code in TypeScript?

I am currently puzzled about the execution of code in files. Let's say we have a file1.ts with the following content: export interface myInterface {} export function myFunction() {} export const myConst: {} // ... and more exports // top-level non- ...

[Angular 6]Injecting dynamic code into a component

Is there a way to include HTML code within a component that will be interpreted at the component level rather than at the parent level? For instance, <custom-tag>Greetings {{variableInsideComponent}}</custom-tag> where variableInsideComp ...

Monorepo with Yarn workspaces using Typescript and Node.JS project encounters "module not found" error while running nodemon

After creating a monorepo with yarn workspaces for a TypeScript Node.js project, I encountered an issue with local development. Despite successfully building the project, I faced errors when running yarn dev without first manually running yarn build. The e ...

Can you explain the distinction between implementing tab content styles?

My method for displaying tab content is as follows: <mat-tab-group> <mat-tab label="First"> <ng-template matTabContent> The First Content </ng-template> </mat-tab> </mat-tab-group> What sets this apar ...

What is the most suitable data type to represent an empty object?

When I declared the return type of the function below as {}, eslint flagged an error stating not to use {} as a type because it actually means "any non-nullish value". After understanding the meaning behind this error, I realize that specifying return typ ...

Guide to publishing with Chromatic in a Storybook Angular NX workspace

Hey there, I'm looking for some help with running Storybook Chromatic in an NX workspace. My Angular application and libraries are functioning properly when served locally, and I've been able to run stories for my projects without any issues. I ...

Exploring the power of global injectors in Angular 7 for component inheritance

Recently, I have been following a method outlined in a blog post on MSDN to simplify the extension of components without having to include all dependencies in the super() call. However, this approach seems to have ceased working in Angular 7 with Typescrip ...

Step-by-step guide: Setting up Typescript with npm on your local machine

I am trying to set up Typescript without any global dependencies. To do so, I have included the following in my package.json file: { "name": "foo", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \" ...

The functionality of Angular 4 routing is limited to directing to just one subsequent route at

I am encountering a peculiar problem with Angular 2 routing. I can successfully navigate to the next page, but for some reason, I am unable to navigate from that page. My application consists of 4 components: Home, Search Result, Profile, and Admin. Upon ...

Issues with Vercel deployment/building are occurring. The error message states: "Failed to compile. Type error: Unable to locate module ... or its associated type declarations

I'm attempting to launch my initial Next.js application using Vercel. Even though the app runs smoothly on my local machine (it builds locally with yarn run build and I can develop normally using yarn run dev), I am encountering issues with the build ...

Rearrange list items by dragging and dropping

Here is the HTML and TypeScript code I have implemented for dragging and dropping list items from one div to another: HTML: <div class="listArea"> <h4> Drag and Drop List in Green Area: </h4> <ul class="unstyle"> <l ...

How to disable click event binding in Angular2 after it has been clicked once

Within my application, there is a button that has a click event attached to it: <button class="btn btn-default" (click)="doSomething()"> I am wondering if there is a way to remove the (click) event from the button within the doSomething method so t ...

What steps should be taken to properly utilize the useRef hooks in this code snippet?

I've been working on a beer wishlist project using React. However, I encountered an issue with the following error message: TS2786: 'EditBeerPage' cannot be used as a JSX component. Its return type 'Element | undefined' is not a ...

What is the best approach for transferring non-string objects between routes in Angular?

I am currently developing a custom file viewer. To achieve this, I have created a specialized component known as FileBrowserComponent that is specifically designed to be displayed when the route /files is accessed. When navigating, I include a query param ...

Toggle visibility between 2 distinct Angular components

In my application, I have a Parent component that contains two different child components: inquiryForm and inquiryResponse. In certain situations, I need to toggle the visibility of these components based on specific conditions: If a user clicks the subm ...