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

如何在非独立组件中使用Angular模块?

解决“imports仅在独立组件上有效”错误

问题原因

你的组件不是独立组件(未设置standalone: true),这类组件不能在自身的@Component装饰器里使用imports数组,只能通过所属的NgModule来导入依赖模块。

两种解决方式


方式1:转为独立组件

如果想让组件直接导入模块,修改组件的@Component配置,添加standalone: true,同时保留组件内的imports数组:

@Component({
  selector: 'your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css'],
  standalone: true, // 添加这行开启独立组件模式
  imports: [MatExpansionModule] // 保留组件内的模块导入
})
export class YourComponent { ... }

这种情况下,不需要在app.module.ts的declarations里声明该组件,独立组件会自动被Angular识别。

方式2:在NgModule中导入模块(适合非独立组件)

如果不想转为独立组件,删除组件内的imports数组,然后在app.module.ts(或该组件所属的feature module)中导入MatExpansionModule:

// app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { MatExpansionModule } from '@angular/material/expansion'; // 导入Material模块

import { YourComponent } from './your-component/your-component.component'; // 导入你的组件
import { AppComponent } from './app.component';

@NgModule({
  declarations: [
    AppComponent,
    YourComponent // 声明你的组件
  ],
  imports: [
    BrowserModule,
    MatExpansionModule // 将模块添加到NgModule的imports数组中
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

确保组件的@Component配置中没有imports数组和standalone: true属性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 11:14:53