简体   繁体   English

Angular2重用组件

[英]Angular2 Reusing Components

I have common components in my app like header, dialogBox, etc that I use in other components. 我的应用程序中有一些通用组件,例如标头,对话框等在其他组件中使用的组件。 They way I do it right now is I simply use them as HTML tags whenever I need. 我现在使用它们的方式是,只要有需要,我就简单地将它们用作HTML标记。 For example if my header component's selector is 'app-header' , everytime I want to include header I use <app-header></app-header> . 例如,如果我的标头组件的选择器是'app-header' ,则每次要包含标头时,我都会使用<app-header></app-header>

I feel like this is not the right way of doing it, because Angular has thing called ViewChild which supposedly do the same thing. 我觉得这不是正确的方法,因为Angular有一个叫做ViewChild的东西,据说可以做同样的事情。 However, when I try to use ViewChild I get the same error as discussed here: https://github.com/angular/angular/issues/5415 但是,当我尝试使用ViewChild时,出现与此处讨论的相同的错误: https : //github.com/angular/angular/issues/5415

Looks, like your problem is completely different from the problem from issue 5415 (your link).. 看起来,您的问题与问题5415(您的链接)完全不同。

If you want to have always some components on your page and just some replacement - you need to use a Router. 如果要始终在页面上保留某些组件,而只需要进行替换,则需要使用路由器。

https://angular.io/docs/ts/latest/guide/router.html https://angular.io/docs/ts/latest/guide/router.html

I think you just need to add the child component selectors in the template for the parent component. 我认为您只需要在父组件的模板中添加子组件选择器。 Once done this way, the child components will appear whenever you use the parent component. 一旦以这种方式完成,子组件将在您使用父组件时出现。 I have been doing this in my angular 2 projects and this works. 我在我的Angular 2项目中一直在这样做,并且可以正常工作。 Let me know if my understanding about your problem is correct. 让我知道我对您问题的理解是否正确。 Cheers, Abhi 干杯,阿比

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

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