You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular独立组件中如何全局引入CommonModule?

全局导入CommonModule到所有Angular独立组件的方法

方法1:应用启动时全局注册

在main.ts的应用启动配置中,通过importProvidersFrom将CommonModule全局导入,这样所有独立组件无需手动导入就能使用NgIf、NgFor等指令:

import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
import { importProvidersFrom } from '@angular/core';
import { CommonModule } from '@angular/common';

bootstrapApplication(AppComponent, {
  providers: [
    importProvidersFrom(CommonModule)
  ]
});

方法2:创建共享基础模块

如果需要统一管理多个常用依赖,可创建一个共享基础模块,导出CommonModule及其他常用模块,后续组件只需导入这个基础模块即可:

// shared/base.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  exports: [CommonModule, ReactiveFormsModule]
})
export class BaseModule {}

组件中导入示例:

@Component({
  selector: 'app-register',
  standalone: true,
  imports: [BaseModule, TextInputComponent],
  templateUrl: './register.component.html',
  styleUrl: './register.component.scss'
})

注意:全局注册后所有独立组件默认拥有CommonModule指令的使用权,若需在部分组件中隔离依赖,更推荐使用共享基础模块的按需导入方式。

内容的提问来源于stack exchange,提问作者GuilhermeMarques

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 02:19:52