Angular实习新手遇NgbDropdown注入错误,求动态下拉菜单配置
Angular ngBootstrap动态下拉菜单报错排查
问题详情
Angular实习新手,在配置ngBootstrap动态下拉菜单时触发以下错误:
ERROR NullInjectorError: R3InjectorError(AppModule)[NgbDropdown -> NgbDropdown -> NgbDropdown]: NullInjectorError: No provider for NgbDropdown
父组件HTML代码
<div class="container" id="container"> <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" ngbDropdownToggle> Dropdown button </button> <div app-city-details-component *ngFor="let city of cityArray" [city]="city" ngbDropdownMenu> </div> </div>
子组件HTML代码
<div class="container" id="container" ngbDropdownItem> <button class="button" type="button" (click)="handleClick()"> <p>{{city.name}}</p> <p>Latitudine: {{latitudine}}</p> <p>Longitudine: {{longitudine}}</p> <p>Timezone: {{timezone}}</p> <div app-show-weather-conditions [weather]="currentRealWeather"></div> </button>
模块配置情况
从提供的app.module.ts截图来看,模块中未导入NgbDropdownModule。
错误原因与修复方案
核心问题
报错提示缺少NgbDropdown的提供者,本质是使用下拉组件的模块未导入ngBootstrap的下拉菜单模块,Angular无法识别相关指令。
修复步骤
- 确认依赖安装:如果未安装
@ng-bootstrap/ng-bootstrap,先执行安装命令:npm install @ng-bootstrap/ng-bootstrap bootstrap - 导入下拉模块:在
app.module.ts中添加NgbDropdownModule的导入:import { NgbDropdownModule } from '@ng-bootstrap/ng-bootstrap'; @NgModule({ imports: [ // 保留原有导入模块 NgbDropdownModule ], // 其他模块配置(声明、提供者等) }) export class AppModule { } - 修正组件结构:原父组件的HTML结构存在逻辑错误,
ngbDropdownMenu不应放在循环的子组件上,且父容器缺少ngbDropdown指令,正确结构如下:
该结构确保只有一个下拉菜单容器,循环生成的子组件作为菜单选项存在,符合ngBootstrap的组件规范。<div class="container" id="container"> <div ngbDropdown class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" ngbDropdownToggle> Dropdown button </button> <div ngbDropdownMenu> <app-city-details-component *ngFor="let city of cityArray" [city]="city"></app-city-details-component> </div> </div> </div>
内容的提问来源于stack exchange,提问作者marcom966
相关产品推荐
相关产品推荐

