首页 新闻 会员 周边 捐助

Angular 项目使用 Standalone Components 时如何全局 import CommonModule

0
悬赏园豆:30 [已解决问题] 解决于 2024-12-29 12:32

园子博客后台升级到 angular 19 后,将所有 component 都迁移到 standalone component,然后发现连最简单的 *ngIf[ngClass] 无法使用

build 出现警告与错误:

[WARNING] NG8103: The `*ngIf` directive was used in the template, but neither the `NgIf` directive nor the `CommonModule` was imported.

Error occurs in the template of component CollapsePanelComponent.
Can't bind to 'ngClass' since it isn't a known property of 'div'.

需要专门在 component 中 import

import { NgClass, NgIf } from '@angular/common';

@Component({
    imports: [NgIf, NgClass],
    selector: 'cnb-collapse-panel',
    templateUrl: './collapse-panel.component.html',
    styleUrls: ['./collapse-panel.component.less']
})

这样要修改很多 component,很麻烦,请问如何全局 import CommonModule?

dudu的主页 dudu | 高人七级 | 园豆:28727
提问于:2024-12-29 11:07
< >
分享
最佳答案
0

不支持全局 import,只能一个一个组件 import

stackoverflow 上有人问了同样的问题 With the new standalone feature in Angular, is there not a way to provide all CommonModule imports during bootstrap?

有人给出了答案:

This is how standalone has been design : explicit dependencies. You import an component/directive you wish to use.

For ngIf/ngFor/ngSwitch the alternative is the use the new built-in control flow which doesn't require any directive import.

dudu | 高人七级 |园豆:28727 | 2024-12-29 11:33

main.ts 使用 standalone bootstrapping api 不支持全局 import

bootstrapApplication(AppComponent, appConfig)
    .catch((err) => console.error(err));

如果实在想全局 import,可以使用兼容 NgModule 的 api

document.addEventListener('DOMContentLoaded', () => {
  platformBrowserDynamic()
    .bootstrapModule(AppModule)
    .catch((err) => console.error(err));
});
dudu | 园豆:28727 (高人七级) | 2024-12-29 12:32
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册