【发布时间】:2022-06-28 13:21:51
【问题描述】:
Angular 14 引入了新的 独立 组件,不需要使用任何模块。如果在库中提供这些组件,如何使用这些组件?在标准的非独立组件中,我们首先必须导入给定的模块。 Angular 如何识别我正在导入的组件来自这个特定的包?
【问题讨论】:
-
这是否会以这种方式工作,我必须将这样一个独立的组件导入我想在其中使用它的模块?
Angular 14 引入了新的 独立 组件,不需要使用任何模块。如果在库中提供这些组件,如何使用这些组件?在标准的非独立组件中,我们首先必须导入给定的模块。 Angular 如何识别我正在导入的组件来自这个特定的包?
【问题讨论】:
要制作一个独立的组件,你需要在组件的装饰器中使用standalone参数将组件定义为standalone,然后你也可以在组件中使用imports语句。然后,您的组件将如下所示。
@Component({
standalone: true,
imports: [CommonModule],
selector: 'example-component',
template: `./example.component.html`,
})
export class ExampleComponent {}
接下来您需要将该组件导入到其他组件/模块中。您现在可以将它导入到您的模块中的 import 属性中,这是以前不支持的。或者你可以将它导入到另一个根本不支持的组件中,现在支持了。
// Importing using a Module
@NgModule({
imports: [ExampleComponent]
})
export class MyModule {}
// Importing using a component
// This component also needs the standalone property
@Component({
standalone: true,
imports: [ExampleComponent],
selector: 'some-component',
template: `./component.html`,
})
export class ExampleComponent {}
【讨论】:
如果你想在另一个组件A中使用独立组件,你需要在组件A中导入独立组件,如下所示,
@Component({
standalone: true,
imports: [StandaloneComponent],
selector: 'demo-component',
template: `./demo.component.html`,
})
【讨论】: