在Angular4(RC5)中嵌套组件

时间:2017-08-27 17:46:15

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

进入Angular并观看一个过时的教程,这个教程实际上适用于Angular2(我知道)。

Angular4:

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

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

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 {}

注意:省略了导入声明

1 个答案:

答案 0 :(得分:0)

在某些时候(我很久以前就忘记了每天出现的不同版本),他们转而采用基于模块的设计,并且基本上在一夜之间取消了directives

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

之后,您根本不需要组件中的directives部分。

简而言之:

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