为什么在Angular中,必须在app.module.ts中导入模块,为什么不能在组件中直接导入模块?

时间:2019-07-04 14:36:24

标签: angular import module components export

基本上,我是从here学习Angular的。

我在app.module.ts中知道了,我必须导入FormsModule

像下面的代码片段

// At app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {ReactiveFormsModule} from "@angular/forms"
// import {FormsModule} from "@angular/forms";          // Commented purposly to check
import { CommonModule } from '@angular/common';


import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HeroesComponent } from './heroes/heroes.component';

@NgModule({
  declarations: [
    AppComponent,
    HeroesComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    // FormsModule,          // Commented purposly to check
    CommonModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

现在我必须在app.module.ts中执行此导入,以使其运行示例

从“ @ angular / forms”导入{FormsModule};

但是为什么不能直接将它们导入heroes.component.ts组件中(请查看上面提到的链接中的示例)?

类似于下面的代码段

// At heroes.component.ts

import { Component, OnInit } from '@angular/core';
import {Hero} from "../modelClasses/hero";
import {FormsModule} from "@angular/forms"; //**Despite its imported my example is not working if I comment in FormsModule in app.module.ts


@Component({
  selector: 'app-heroes',
  templateUrl: './heroes.component.html',
  styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {

  hero : Hero = {id: 1,
          name: "Windstorm" }

  constructor() { }

  ngOnInit() {
  }

}

因为根据我的理解,模块和组件是任何角度应用程序的两个不同概念构建块,其中模块封装了许多组件服务指令,而组件是系统的一小部分。

但是,如果一个类带有组件注释,这是否意味着它不能直接导入模块?

因为毕竟,一个类和模块的工作方式就像一个包,所以从包中理想地导出的类应该可以导入到另一个类中。

可以帮助理解为什么我必须专门在app.module.ts文件中导入这种方式吗?

0 个答案:

没有答案
相关问题