【问题标题】:Nesting components in Angular4 (RC5)在 Angular4 (RC5) 中嵌套组件
【发布时间】:2017-08-27 17:46:14
【问题描述】:

进入 Angular 并观看一个实际上是针对 Angular2 的过时教程(是的,我知道)。

Angular4:

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ AppComponent , MyChildComponent ],
  bootstrap: [ AppComponent ]
})

似乎这就是您现在嵌套组件的方式,但没有办法在 Angular 2 中完成(或类似地)它吗?因为您可以将它直接导入根组件中现已弃用的“指令”属性中(发现这对于快速开发非常方便)。

Angular2:

@Component({
   selector: 'app-root',
   directives: [MyChildComponent]
   template: '<div><ChildComponent></ChildComponent></div>'
})
export class AppComponent {}

编辑:这是 MyChildComponent 声明(仍然是 Angular2 的一部分):

@Component({
   selector: 'ChildComponent',
   template: '<h2>Child component</h2>'
})
export class MyChildComponent {}

注意:省略了导入声明

【问题讨论】:

  • 您在组件内将其定义为directive。指令和组件如何拥有相同的类?
  • 不一样。 MyChildComponent 的声明不在此处。我会更新它以避免混淆。这不是“不工作”类型的问题。只是想知道他们是否有其他东西而不是 Angular 4 中的“指令”(在 Angular 2 中存在,现在已弃用)关键字。
  • 更新了我的问题

标签: angular deprecated angular2-directives angular-components angular-rc5


【解决方案1】:

在某个时候(很久以前,我忘记了每天都会弹出不同的版本)他们转向基于模块的设计,并且基本上在一夜之间取消了directives

为了在任何地方使用您的组件,您只需要在模块中的 declarations: [...] 部分填充您在该模块中的组件。

之后,您就不再需要组件中的directives 部分了。

简而言之:

  • 模块的declarations 部分中列出的任何组件都将使这些组件可供该模块的所有其他组件使用
  • 模块的exports 部分中列出的任何组件都将使这些组件可用于imports 该模块的任何其他模块。

【讨论】:

  • 最好让他们在那里。更容易扩展和维护。谢谢你的回答
猜你喜欢
  • 2018-05-29
  • 1970-01-01
  • 2017-12-31
  • 1970-01-01
  • 2018-09-19
  • 2018-01-21
  • 2018-02-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多