Error in Angular: Unable to bind FormControl to input due to unexpected issue

I need help resolving a common error I'm encountering. I have forms in two different sections of my application, and while the form functions correctly in one section, it is not working in the other. Both ReactiveFormsModule and FormsModule are imported.

resolution.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { ResolutionRoutingModule } from './resolution-routing.module';
import { ResolutionComponent } from './resolution/resolution.component';
import { ResolutionDetailComponent } from './resolution-detail/resolution-detail.component';
import { ResolutionListComponent } from './resolution-list/resolution-list.component';
import { NewResolutionComponent } from '../../forms/new-resolution/new-resolution.component';
import { MatFormFieldModule } from '@angular/material/form-field';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatDialogModule } from '@angular/material/dialog';
import { MatInputModule } from '@angular/material/input';
import { MatSelectModule } from '@angular/material/select';
import { MatCardModule } from '@angular/material/card';
import { ResolutionEditComponent } from '../../forms/resolution-edit/resolution-edit.component';


@NgModule({
  declarations: [ResolutionComponent,
  ResolutionDetailComponent,
  ResolutionListComponent,
  NewResolutionComponent,
  ResolutionEditComponent],
  imports: [
    CommonModule,
    ResolutionRoutingModule,
    MatFormFieldModule,
    ReactiveFormsModule,
    MatDialogModule,
    FormsModule,
    MatInputModule,
    MatSelectModule,
    MatCardModule
  ]
})
export class ResolutionModule { }

The form in the NewResolutionComponent works without errors.

new-resolution-component.html(snippet: showing one input field)

<form (ngSubmit)='onSubmit()'[formGroup]='ResolutionFormGroup'>
<mat-form-field>
        <mat-label>Title</mat-label>
        <input [formControl]='TitleControl' matInput placeholder="Title" required/>
</mat-form-field>

...

</form>

new-resolution.component.ts

import { Component, OnInit } from '@angular/core';
import { AbstractControl, FormControl, FormGroup, Validators } from '@angular/forms';
import { MatDialogRef } from '@angular/material/dialog';
import { AuthService } from '../../shared/services/auth.service';
import { ResolutionsService } from '../../shared/services/resolutions.service';

@Component({
  selector: 'app-new-resolution',
  templateUrl: './new-resolution.component.html',
  styleUrls: ['./new-resolution.component.scss']
})
export class NewResolutionComponent implements OnInit {
  uid: string
  category_id: string
  title: string
  description: string
  catId: string
  categoryList = []

  TitleControl: AbstractControl
  DescriptionControl: AbstractControl
  UserIdControl: AbstractControl
  CategoryControl: AbstractControl
  ResolutionFormGroup: FormGroup

...

In contrast, when replicating the form setup in another file like resolution-edit.component.html, I encountered an issue with the placeholder text not displaying as expected:

resolution-edit.component.html(showing one input, similar to previous component)

<form formGroup='ResEditGroup'>
    <mat-form-field>
        <mat-label>Title</mat-label>
        <input [FormControl]='TitleControl' matInput placeholder="Title" required/>
    </mat-form-field>

After analyzing the components, I noticed that using '[ ]' around 'FormControl' caused an error message:

Can't bind to 'FormControl' since it isn't a known property of 'input'.

resolution-edit.component.ts

import { Component, Inject, OnInit } from '@angular/core';
import { AbstractControl, FormControl, FormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';

@Component({
  selector: 'app-resolution-edit',
  templateUrl: './resolution-edit.component.html',
  styleUrls: ['./resolution-edit.component.scss']
})
export class ResolutionEditComponent implements OnInit {
...

To ensure consistency with the first component's behavior, make sure to only use 'formControl' instead of '[formControl]' to display the desired placeholder text ('SUPERBAD'), as demonstrated in the initial form setup.

Answer №1

Let's start by refactoring the code to make it more concise before addressing any issues.

import { Component, Inject, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';

**resolution-edit.component.ts**

@Component({
  selector: 'app-resolution-edit',
  templateUrl: './resolution-edit.component.html',
  styleUrls: ['./resolution-edit.component.scss']
})
export class ResolutionEditComponent implements OnInit {
  resEditGroup = this.fb.group({
     title: ['SUPERBAD', [Validators.required]],
     description: ['', [Validators.required]]
  })
  constructor(
    private fb: FormBuilder,
    // @Inject(MAT_DIALOG_DATA) data
    ) {
    // this.descriptionInput = data.description
    // this.titleInput = data.title
   }

  ngOnInit(): void {
  }

}

You can now use resolution-edit.component.html

<form [formGroup]='ResEditGroup'>
    <mat-form-field>
        <mat-label>Title</mat-label>
        <input formControlName='title' matInput placeholder="Title" required/>
    </mat-form-field>

Here are some changes that have been implemented:

  1. The usage of a FormBuilder to create the FormGroup, eliminating the need for manual creation of new instances
  2. Transition to camelCase naming convention
  3. important Binding to the FormGroup using [] and specifying control names with formControlName as strings ensures proper binding to ResEditGroup

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

Forwarding parameter data type

I am facing an issue with 2 navigation points leading to the same screen 1. this.router.navigate([this.config.AppTree.App.Module.Details.Path], { state: { data: { id: this.TableId } } }); this.router.navigate([this.config.AppTree.App.Module.Details.Pa ...

incapable of altering the function of individual parts within ionic 3

I am currently working on creating a list of people for users to connect with. When a user clicks on the connect button, it should send a connection request to the chosen person. However, I am facing an issue where clicking on the connect button changes th ...

Saving large amounts of data in bulk to PostgreSQL using TypeORM

I am looking to perform a bulk insert/update using TypeORM The Test entity is defined below: export class Test { @PrimaryColumn('integer') id: number; @Column('varchar', { length: 255 }) testName: string; } I have the f ...

Using Angular 2 to Bind a Single Click Event to Multiple Elements

Within the component's export class, I have defined iconCheck: string;. In the constructor, I set this.iconCheck = "add_circle";. Additionally, in the export class, I have the following method: iconChange() { if(this.iconCheck == "add_circle") { ...

Is there a way to customize the default styles of Kendo UI for Angular?

Is it possible to customize the default datepicker styles to look like the design in the second image? https://i.sstatic.net/h8yfA.png https://i.sstatic.net/PfiSf.png ...

Could you please explain the specific distinctions between pipe and map within Angular 7?

After extensive research, I'm still struggling to understand the distinction between pipe and map in Angular 7. Should we always include a pipe in Service.ts file in Angular 7? Appreciate any clarification on this matter. ...

Identify duplicate values in an array by comparing pairs of elements

If the array contains the data shown below: let array = [{ name: "Ramesh", SalseVersion: 10, MarketingCode: 11 }, { name: "Suresh", SalseVersion: 12, MarketingCode: 13 }, { name: "Siva", SalseVersion: 10, MarketingCode: 14 }, { na ...

Please ensure that the function chain has appropriate parameter and return types by specifying the tuple type

Can a new type be created for the given tuple/array that has certain validation constraints? The following array is considered valid: const funcs = [(a: string) => 1, (a: number) => 'A', (a: string) => 2] However, this one is invalid ...

The data type 'HTMLCollection | undefined' is required to have a method called '[Symbol.iterator]()' which will then return an iterator

I'm currently working on creating a custom date-picker using web components by following a tutorial. I've encountered an error while translating the JavaScript logic to Typescript, specifically within the connectedCallback() {...} function. The e ...

What are the counterparts of HasValue and .Value in TypeScript?

There is a method in my code: public cancelOperation(OperationId: string): Promise<void> { // some calls } I retrieve OperationId from another function: let operationId = GetOperationId() {} which returns a nullable OperationId, operat ...

What could be the reason for SVGR not producing a TypeScript declaration file in my esbuild setup?

I have been working on developing a custom SVG icon library using TypeScript. So far, the SVGR tool has been quite useful in creating components from SVG imports. However, I am encountering an issue with generating types that would allow me to pass attribu ...

Steps for appending a string to a variable

Currently working on creating a price configurator for a new lighting system within homes using Angular 7. Instead of using TypeScript and sass, I'm coding it in plain JavaScript. Page 1: The user will choose between a new building or an existing one ...

Using TypeScript to specify data types in the Vue data object

I am currently utilizing Vue.js with Typescript in a webpack project. Following the guidelines provided in the Recommended Configuration in my tsconfig.json, I have set: "strict": true, Within one of my components, I have: declare interface P ...

Ways to ensure that DOM elements have completed rendering in Angular 2 Unit Tests

I am currently working on a test that focuses on an HTML element, sets its value, and triggers the blur event handler. The blur event is supposed to initiate a validation check which, if invalid, should disable a save button. During a test run, this proce ...

What is the best way to implement a dynamic mask using imask in a React

I have a question regarding the implementation of two masks based on the number of digits. While visually they work correctly, when I submit the form, the first mask is always selected. How can I resolve this issue? My solution involves using imask-react ...

Transforming this JavaScript function using Template Strings into TypeScript

Is there anyone out there who can assist with the following query? I have a functional .js file that I need to integrate into a TypeScript program. import React from "react"; import styled, { css } from "styled-components"; const style = ({ theme, ...res ...

Exploring the Global Reach of Angular 9

I have been working on updating our current app to implement internationalization using the new approach in Angular 9. Below is how I set it up in the angular.json file: { ... "projects": { "viewer": { ... "i18n": { "sourceLocale": ...

Updating an object within an array of objects in Angular

Imagine having a unique object array named itemArray with two items inside; { "totalItems": 2, "items": [ { "id": 1, "name": "dog" }, { "id": 2, "name": "cat" }, ] } If you receive an updated result for on ...

Tips on adding a generic type to a utility function designed for comparing object values

Looking for assistance with the syntax issue I'm encountering on this line: arr2.some((arr2Obj) => arr2Obj[identifier] === arr1Obj[identifier]) // Type 'U' cannot be used to index type 'T' I'm attempting to create a funct ...

Storing a value received from an observable into a component variable in Angular 4 using the subscribe method

I am attempting to save the value from an observable into a variable within the component by utilizing a service. However, the variable always ends up as undefined. When I check "names" inside the subscribe function, it does contain the expected value. ...