簡體   English   中英

如何從 Angular 14 的庫中導入獨立組件?

[英]How to import standalone components from a lib in Angular 14?

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`,
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM