将组件信息传递给另一个组件

时间:2017-12-20 09:18:48

标签: html angular

我有多个组件及其html页面,每个页面包含标题,页面类型(副标题)和id。现在,我没有将这些信息添加到每个页面,而是希望创建一个包含此特定信息的组件,并将其作为选择器添加到所有组件中,这样我就可以统一并控制每个页面上的结构。我还需要在点击后将一些内容路由到另一个页面。

我正在查看它的方式是将包含标题,副标题和ID的DetailComponent将被视为我相信(?)的父组件,而来自所有其他页面的我将作为子项发出所需信息组件。如果我错了,请纠正我。不确定我想要的这种结构是父子关系还是兄弟姐妹。

所以在子组件html页面中我会:

<detail-component [pagetitle] = "page.title" [pageId]="page.id"></detail-component>

in child component.ts:

@Output()
public pageInfo: new EventEmitter<any>();

this.pageInfo.emit({...})  
DetailComponent.html中的

<div>
   <h1>{{page.title}}</h1>
   <h2>{{page.subTitle}} " - " {{page.Id}}</h2>
</div>

我将所有这些连接在一起以获得我想要的东西并且有任何帮助将会受到赞赏。

页面示例,我有五个这样的页面,每个html页面都是从它组件填充的:

<div class="pageInfo">
<h2>{{Title}}Title of this page here</h2>
<h3>{{ID}}:{{Subtitle}} Subtitle of page here</h3>
</div>

我想将这个html移动到父html页面然后从每个子组件我将发出我需要的信息,如标题,id和副标题到父组件,并从子html页面我想用

替换标题信息html

2 个答案:

答案 0 :(得分:0)

基本上你的逻辑很好,但是你省略了(pageInfo)="..."所以添加到你的子html选择器。

<detail-component [pagetitle]="page.title" [pageId]="page.id" (pageInfo)="handlePageInfo($event)"></detail-component>

但是,如果它是多嵌套的子节点,那么处理数据可能会有点痛苦。您始终可以将其与@Injectable服务结合使用,但是在组件之间建立连接也会很痛苦。对于@Input @Output解决方案,每个child都应具有属性,如果它具有parent。制作一个while循环,直到它没有parent

答案 1 :(得分:0)

你要创造的是父母与子女的关系。你可以做的就是一个包含多个组件的单个页面:

<强> ------------

童车

那你怎么能这样做:

在父HTML中:

<detail-component *ngIf="child1" [pagetitle] = "page.title" [pageId]="page.id"></detail-component>
<detail-component2 *ngIf="child2" [pagetitle] = "page.title" [pageId]="page.id"></detail-component2>
<detail-component3 *ngIf="child3" [pagetitle] = "page.title" [pageId]="page.id"></detail-component3>

像这样你将child1或2或3置于true并将数据放入其中(可以是不同的值和变量)。

要发回信息,可以使用 @Output ,例如:

<detail-component *ngIf="child1" [pagetitle] = "page.title" [pageId]="page.id" (output)="setOutput($event)"></detail-component>

在父母身上有一个功能:private setOutput(_output){ //play with output here