What is the purpose of importing a module in app.module.ts? And what specifically happens when importing classes one by one in the

I am interested in creating an Angular form, but I have a question about why we import 'ReactiveFormsModule' in app.module. Additionally, I am curious as to why we need to explicitly import classes like FormControl and FormGroup again in the template class.

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { ReactiveComponent } from './reactive/reactive.component'; <-- component class

import { ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';


@NgModule({
  declarations: [
    AppComponent,
    ReactiveComponent
  ],
  imports: [
    ReactiveFormsModule,
     .....
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Reactive.Component.ts

import { Component, OnInit } from '@angular/core';
**import { FormControl } from '@angular/forms';** <---why is this needed as we have already imported forms module in app.module.ts

@Component({
  selector: 'app-reactive',
  templateUrl: './reactive.component.html',
  styleUrls: ['./reactive.component.css']
})
export class ReactiveComponent  {

  name = new FormControl('');
  
  constructor() { }

  ngOnInit(): void {
  }

}

What exactly does importing FormsModule in app.module.ts achieve? And what is the significance of importing each class separately in the component class?

Answer №1

When you import a module in app.module.ts, you are able to bring in modules from node_modules. The modules that are declared in app.module.ts can be accessed by any component within an angular app. Depending on the requirements of classes in different components of angular, we instantiate classes as needed. For example, when working with forms, you might call FormGroup which takes you to the forms.d.ts file where the formgroup class is declared and made exportable.

If FormsModule is removed from app.module.ts, every package installed in node_modules must still be declared within app.module.ts to be used in any component. Components simply call the instance as necessary. If it were possible to only declare reactive forms in app.module.ts, then the entire package would need to be imported into the app, resulting in a heavier application that runs slower.

The FormGroup class retrieves its instance from forms.d.ts through the inclusion of FormsModule in app.module.ts.

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

"Despite modifying the ID in the response data of Angular MongoDB, the request data ID remains unchanged

Having trouble with managing requests and responses, specifically when a customer tries to add multiple items of the same product but in different sizes. The initial step involves checking if the ID exists by using a count and an if statement. If it exists ...

What is the reasoning behind AngularJS 2 HTTP Post only allowing string data as input?

Can someone explain to me why the HTTP Post method in AngularJS 2 (2.0.0-beta.13) only accepts string data as body, unlike in AngularJS 1 where it can accept a JavaScript object? AngularJS-1: $http.post(someUrl,someObject) AngularJS-2: http.post(someUr ...

Encountering issues with nested routes in Angular 2 causing errors

Currently, I am developing a web application using Angular 2 in an ASP.NET Core environment. The landing page is set at the base URL and has its own Layout file, Index page, and controller. My goal is to include a new section on my website located at /too ...

Tips for obtaining the most recent HTML element in Angular

I was able to include HTML content in an Angular (7) UI using the DomSanitizer this.sanitizer.bypassSecurityTrustHtml("htmlstr") Once the content is sanitized and displayed in the HTML view, users have the ability to modify the values as desired ...

Learn the dynamic binding method for <a href> templates in Angular 2!

Kindly review the code snippet provided below: Component.ts getReply():string{ if(condition){ return "The link is: <a href = 'https://www.google.com'>Google</a>"; } } In my front end, I am using [innerHtml] to bind ...

Error: Failed to retrieve the name property of an undefined value within the Array.forEach method

Upon pressing the button to display the task pane, I encountered an error message in the console window that reads: "Uncaught (in promise) TypeError: Cannot read property 'name' of undefined". This error persists and I am unable to resolve or com ...

Troubleshooting the Ng2-Charts Linechart to display all values instead of just the first two

Starting a new Angular application with the Angular-CLI (beta 22.1) has presented an issue when adding test data (5 values) to a chart. The scaling appears incorrect, displaying only the first two values stretched across the entire length of the graph (ref ...

Is it advisable to move operations outside of the useEffect hook?

Is it advisable to move code outside of the useEffect function in React? function BuyTicket(props: any) { useEffect(() => { //.. }, [eventId, props.history]); // IS IT RECOMMENDED TO PUT CODE HERE? const userNameL ...

The TypeScript compiler does not make assumptions about variable types within an if statement

I'm currently tackling the challenge named 'Merge Two Binary Tree' on leetcode with TypeScript. My solution is passing the tests successfully, but the compiler is throwing an error that says: What's puzzling me is that I believe I&apos ...

A step-by-step guide on injecting dependencies manually in NestJS

When working with Angular, it is possible to access and inject dependencies manually using the built-in Injector class. This allows you to access and inject services without having to pass them through the constructor. Essentially, you can inject a service ...

Using Cypress fixtures with TypeScript

After transitioning from using Cypress with Javascript specs to Typescript, I encountered a challenge in working with Fixtures. In Javascript, the approach below worked; however, I faced difficulties when switching to Typescript. Fixture JSON file: I sto ...

Switching out a traditional class component with a functional component within a hook to deduce properties from T

One challenge is to subtract props from T within the withHookFn function using a function instead of a class as successfully done in the withHook function. The code contains comments explaining this issue. Dive into the code for more insights. import Reac ...

Using Angular material to display a list of items inside a <mat-cell> element for searching

Can I use *ngFor inside a <mat-cell> in Angular? I want to add a new column in my Material table and keep it hidden, using it only for filtering purposes... My current table setup looks like this: <ng-container matColumnDef="email"> < ...

Don't display div if database has certain value - Angular

Is there a way to determine if a specific value exists in a PostgreSQL database? If so, can I then hide an HTML element based on this information? Can CSS and JavaScript be used to hide elements, or is there another method that should be utilized for hidi ...

Unidirectional data flow from the document object model to the variable within the

When working with Angular, there are multiple methods available for binding variables to DOM properties. You can utilize the `{{}}` syntax, `[property]=expression`, or implement two-way ngModel binding. One aspect that I have not yet discovered is how to ...

Utilizing the arr.push() method to replace an existing value within an array with a new object, rather than simply adding a new

Seeking help to dynamically render a list of components that should expand or shrink based on values being added or removed from an array of custom objects. However, facing an issue where pushing a value into the array only replaces the previous value inst ...

The CORS policy specified in next.config.js does not appear to be taking effect for the API request

I am currently working on a Next.js application with the following structure: . ├── next.config.js └── src / └── app/ ├── page.tsx └── getYoutubeTranscript/ └── getYoutubeTranscript.tsx T ...

Issue with binding background images to DIV elements in Angular 4 CSS

Here is a template example: <div [style.background-image]="profileImage" ></div> In the TypeScript file: We declare private profileImage: any; and use DomSanitizer for security. Fetching photo from service: We set this.profileImage using b ...

The Typescript Decorator is triggered two times

I submitted a bug report regarding Typescript because I suspect there is an issue, although I'm seeking additional insights here as well. This is the scenario. When running the following code: class Person { @IsValueIn(['PETER', ' ...

The technique for accessing nested key-value pairs in a JSON object within an Angular application

After receiving the response from the backend, I have retrieved a nested hash map structure where one hash map is nested within another: hmap.put(l,hmaps); //hmap within hmap When returning the response to the frontend, I am using the ResponseEntity meth ...