园子博客后台升级到 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?
不支持全局 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.
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));
});