Import module in app.module.ts does what and importing class by class in template class does what

Viewed 674

I want to build angular form, I want to know why do we import 'ReactiveFormsModule' in app.module. And then to use different classes like formComtrol, formGroup why do we need to again import them explicitly in 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 {
  }

}

My question importing formsModule in app.module.ts does what? And importing class by class separately in component class does what?

1 Answers

Importing module in app.module.ts helps to import module from node_modules.The modules declared in app.module.ts can be used by any commponent within an angular app.As per the requirements of classes in different components of angular we call the instance of class. In case of forms you can click for eg; FormGroup It takes you to the forms.d.ts inside it the formgroup class is declared and made exportable.

When FormsModule Removed from app.module.ts

Every Package installed within the node_modules should be declared within app.module.ts to use in any component.Components just calls the instance as per requirement.Imagine if it was possible to get reactive forms with only declaring in app.module.ts then the whole package need to be imported within the app which makes apps so heavier it just crawls on execution. Formgroup class calls its instance from forms.d.ts through the medium of FormsModule in the app.module.ts

Related