繁体   English   中英

Angular2 [2.4.10]导入子组件而不声明为AppModule

[英]Angular2 [2.4.10] Import child component without declaring into AppModule

我有两个组成部分

parent.component.ts

@Component({
  selector: 'my-element',
  template: `  <h4>{{title}}</h4>
               <child-element></child-element> //<-- Here I want to take data from child element
              `    
})
export class ParentComponent {
  title = 'This is parent!';
}

child.component.ts

@Component({
  selector: 'child-element',
  template: `
               <h4>{{childTitle}}</h4>
              `   
})
export class ChildComponent {    
  childTitle = 'This is Child';    
}

我尝试在parent.component.ts中添加以下内容,但它不起作用。

@NgModule({
  imports: [ChildComponent],
  providers: []
})

另一个问题 - 如果我有多个组件并希望彼此通信。 在App.module.ts中添加所有这些都会产生开销,不是吗? 因为他们将被装载起来。 如果我错了,请纠正我。

parent.component.ts不应该有@NgModule装饰器。

在你的app.module中,你应该有一个“声明”部分。 与模块关联的所有组件都应包含在声明数组中。

@NgModule({
    declarations: [ParentComponent, ChildComponent]
})

组件可以通过多种方式相互通信。

  • 使用输入绑定将数据从父级传递给子级
  • 父母听儿童活动
  • 父通过局部变量与子进行交互
  • Parent调用@ViewChild()
  • 家长和孩子通过服务进行交流

该网站提供了有关每个选项的更多信息: https//angular.io/docs/ts/latest/cookbook/component-communication.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM