Error shown in console when using Angular 7 FormControlName

My webpage has a reactive form, but I keep encountering an error message that states:

ERROR Error: formControlName must be used with a parent formGroup directive. Make sure to include a formGroup directive and pass it an existing FormGroup instance (you can create one in your class).

I am puzzled by this error because I have already defined a formGroup instance.

This is the HTML code I am using:

<form [formGroup]="singleRecipientForm">
    <textarea #textInput placeholder="user e-mail" formControlName="email"></textarea>
    <button type="submit" (click)="sendMailTextInput(textInput.value)">Send invite </button>
</form

And here is how my Typescript file looks:

singleRecipientForm: FormGroup;

constructor(private formBuilder: FormBuilder) {}

ngOnInit() {
    this.singleRecipientForm = this.formBuilder.group({
      email: ['', [Validators.required]],
    });
}

I cannot figure out why I keep getting this error message.

Answer №1

The error lies in not properly closing the form tag.

 <form [formGroup]="singleRecipientForm">
        <textarea #textInput placeholder="user e-mail" formControlName="email"></textarea>
        <button type="submit" (click)="sendMailTextInput(textInput.value)">Send invite </button>
    </form>

If this is not the issue, make sure you have imported the ReactiveFormsModule in your module.ts file.

Answer №2

When working with Reactive forms, you don't need to use template references to retrieve input values, even though a tag is missing.

singleRecipientForm: FormGroup;

constructor(private formBuilder: FormBuilder) {}

ngOnInit() {
this._buildForm();

}
private _buildForm(): void {
        this.singleRecipientForm = this.formBuilder.group({
      email: New FromControl('', Validators.required)
    });
}
public sendMailTextInput(): any {
console.log(this.singleRecipientForm.value)
}

Your HTML would include (click)="sendMailTextInput()", allowing you to handle the text input as needed. Reactive Forms offer various methods like valueChanges() that can simplify your development process.

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

Issue with Angular 2: Router parameters not showing up in URL

If the URL includes "?edit=true" or "false", I must add that value to my router link. After considering the feedback below, I've updated my code. However, I'm receiving this error "?edit=%5Bobject%20Object%5D". The edit value is not being added ...

There was an unfortunate parsing failure in the module: An unexpected token appeared at position 4

I need help adding the FULLCALENDAR feature to my Angular v14 project. Despite going through all the necessary setup steps, I encountered an unexpected error. Can anyone provide guidance on how to resolve this issue? package.json "@fullcalendar/angul ...

The Hapi response fails to display JSON data in a nested tree format

Hey there! I've got this object with a specific structure. Here it is: interface FolderWithContent { uuid: string name: string; folders: Array<FolderWithContent>; files: Array<Files>; } Just a heads up, Files is an extens ...

Enhance the functionality of 'takeWhile' by incorporating a limit parameter, similar to how 'take' operates

I am attempting to retrieve all pages until either there are no more pages or a certain limit (let's say 10 pages) is reached. If I follow this approach: obs.pipe(expand((page) => { return service.call(page).nextPage; }), take(10), takeWhil ...

Do you have any suggestions for optimizing an Angular 15 reactive form that gets filled with data from an API?

Creating an Angular 15 Reactive Form with FormGroup As I delve into the documentation to construct a form with 4 inputs that are populated with data retrieved via GET requests and then updated upon submission through PUT requests, I find that it is functi ...

Joi has decided against incorporating custom operators into their extended features

I am having trouble extending the joi class with custom operators. My goal is to validate MongoDB Ids, but when I try to use the extended object, I encounter the following error: error: uncaughtException: JoiObj.string(...).objectId is not a function TypeE ...

In the context of Angular applications, how can a state be defined?

Exploring the world of NgRx for the first time and diving into its documentation, I stumbled upon this statement: "State is a single, immutable data structure." In plain terms, what exactly does "state" refer to? Can you provide some basic examples to ...

Understanding React and TypeScript Higher Order Components: How to Resolve the Type '{}' is not assignable to Type P Error

While following along with the Learning React with TypeScript book, I encountered a problem where I hit a wall while coding. Despite surrendering and copying code directly from the book, the compiler is still unhappy As a temporary solution, I have resort ...

Photo captured by camera is not stored in photo gallery

I am currently working on a basic image upload form that allows users to take photos using their phone camera and upload them. However, I have noticed that the pictures taken this way are not being saved to the gallery. Is there something missing in the H ...

Simplified File Paths and Default Files

Currently, I am working with Next.js and TypeScript, setting up path aliases in my project without any issues. However, I'm facing a small difficulty when it comes to dealing with index.ts files within folders. My goal is to achieve something similar ...

Tips for incorporating custom logic into the redirectTo field in Angular

Can I implement custom logic with redirectTo in Angular? Consider the following routes defined using forRoot: const routes: Route[] = [ { path: ':companyId', canActivate: [CanActivateCompany], children: [ { path: '' ...

The Nuxt content Type 'ParsedContent | null' cannot be assigned to type 'Record<string, any> | undefined'

I've been experimenting with @nuxt/content but I'm struggling to create a functional demo using a basic example. ERROR(vue-tsc) Type 'ParsedContent | null' is not assignable to type 'Record<string, any> | undefined'. ...

Encountered an error in React where the declaration file for a module could not be located

New to Typescript and trying to incorporate a splitter into my project. I'm utilizing SplitPane from "react-split-pane/lib/SplitPane" and Pane from "react-split-pane/lib/Pane" in my Typescript project, but encountering an error: Could not find a de ...

Sending updated data from modal back to child component

Within my parent component, I have two child components: Child0 and Display. Child 0 consists of a single button that triggers the opening of a modal where users can select items from a list. The Display component, on the other hand, only contains a label ...

Would it be frowned upon to rely on store instead of data binding for inter-component communication when accessing my data?

Within my current framework, I house the primary business logic within selectors and effects. Components are able to request data by triggering an action that queries the necessary information through selectors. Apart from instances where *ngFor is utili ...

I need to create a login form using Angular - what steps should I follow?

I'm currently in the process of developing a login form for my website. Utilizing angular, express, and mongoDB. Below is the login function controller I have implemented: loginUser: (req, res) => { User.findOne({ username: req.bo ...

Which library do you typically employ for converting .mov files to mp4 format within a React application using Typescript?

As a web programming student, I have encountered a question during my project work. In our current project, users have the ability to upload images and videos. Interestingly, while videos can be uploaded successfully on Android devices, they seem to face ...

Utilize Page.evaluate() to send multiple arguments

I am facing an issue with the Playwright-TS code below. I need to pass the email id dynamically to the tester method and have it inside page.evaluate, but using email:emailId in the code throws an undefined error. apiData = { name: faker.name.firstNa ...

Setting the paths property in a project with multiple tsconfig.json files: a step-by-step guide

My file structure is organized as follows: |__ app1/ | |__ tsconfig.json |__ utilities/ | |__ files.ts |__ base-tsconfig.json I have defined the paths property in base-tsconfig.json like this: "compilerOptions": { "baseUrl": ".", "pa ...

Angular2 date input field unable to restrict minimum and maximum dates

Having trouble with dynamic min and max attributes not being recognized in ionic2 when using the 'datetime-local' type. <ion-input value="" type="datetime-local" [formControl]="expdate" [attr.min]="mindate" [attr.max]="maxdate"></ion-in ...