在 Angular 14 中,如何在独立组件中包含子组件?

Dav*_*ave 0 javascript components module angular angular14

我正在使用 Angular 14。我有一个独立组件,我想在其中包含另一个模块的子组件。独立组件看起来像

<div>
    <child-component></child-component>
</div>
Run Code Online (Sandbox Code Playgroud)

它的服务文件是

@Component({
  selector: 'my-parent-component',
  templateUrl: './parent.component.html',
  standalone: true,
  imports: [
    MyModule
  ]
})
export class ParentComponent {
  ...
}
Run Code Online (Sandbox Code Playgroud)

子组件位于另一个模块中——MyModule。my.module.ts 文件看起来像

/* imports */

@NgModule({
  declarations: [
    ChildComponent
  ],
  imports: [
    ...
  ]
})
export class MyModule { 
  constructor(entityDefinitionService: EntityDefinitionService) {
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)

但我父母的 HTML 给了我错误

    <child-component></child-component>    
Run Code Online (Sandbox Code Playgroud)

线 ...

'app-child-component' is not a known element:
1. If 'app-child-component' is an Angular component, then verify that it is included in the '@Component.imports' of this component.
2. If 'app-child-component' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@Component.schemas' of this component to suppress this message.
Run Code Online (Sandbox Code Playgroud)

Nen*_*vic 5

尝试ChildComponent从导出MyModule,以便您可以在其他地方使用它:

@NgModule({
  declarations: [
    ChildComponent
  ],
  imports: [
    ...
  ],
  exports: [ ChildComponent ]
})
export class MyModule { 
  constructor(entityDefinitionService: EntityDefinitionService) {
    ...
  }
}
Run Code Online (Sandbox Code Playgroud)