使用服务的可重用组件之间的通信
Communication between re usable components using services
我创建了两个 generic components
,名为 1)list 和 2)details,以便我可以重新使用它们:
组件如下所示:
现在我在另一个名为 SCHOOL 和 COLLEGE 的组件中重新使用这些组件,它们将显示如下:
现在
如果我从 SCHOOL 组件中存在的 list
组件单击 list-item
(对于前学校 1)。我想在右侧显示特定点击项目的详细信息(例如:姓名、电子邮件)(即详细信息 page/component)。
如果我从 COLLEGE 组件中的 list
组件单击 list-item
(前大学 1)。我想在右侧显示特定点击项目的详细信息(例如:姓名、电子邮件)(即详细信息 page/component)。
我通过这个 得到了解决方案。在此示例中,组件之间使用 services
进行通信。 但在我的情况下,我正在重新使用组件。我如何在重新使用组件时使用 services
。
Stackblitz DEMO
在您当前的情况下,最好的办法是利用 @Input
和 @Output
装饰器。
You need to have @Input for details component which can get the contact details from its component
@Component({
selector: 'app-details',
templateUrl: './details.component.html',
styleUrls: ['./details.component.css']
})
export class DetailsComponent {
@Input()
public contact;
}
List component will emit the value on selection of any items from the list.
export class ListComponent {
@Output()
public select;
public onSelect(contact){
this.select.emit(contact);
}
}
School and College component can get the the emitted value from the List Component and pass it to details component .
<div class="header">
<h3>SCHOOL</h3>
<div class="left">
<app-list [contacts]="contacts" ></app-list>
</div>
<div class="right">
<app-details></app-details>
</div>
</div>
这是工作副本 - https://stackblitz.com/edit/list-examples-mine-ilxisk
我创建了两个 generic components
,名为 1)list 和 2)details,以便我可以重新使用它们:
组件如下所示:
现在我在另一个名为 SCHOOL 和 COLLEGE 的组件中重新使用这些组件,它们将显示如下:
现在
如果我从 SCHOOL 组件中存在的
list
组件单击list-item
(对于前学校 1)。我想在右侧显示特定点击项目的详细信息(例如:姓名、电子邮件)(即详细信息 page/component)。如果我从 COLLEGE 组件中的
list
组件单击list-item
(前大学 1)。我想在右侧显示特定点击项目的详细信息(例如:姓名、电子邮件)(即详细信息 page/component)。
我通过这个 services
进行通信。 但在我的情况下,我正在重新使用组件。我如何在重新使用组件时使用 services
。
Stackblitz DEMO
在您当前的情况下,最好的办法是利用 @Input
和 @Output
装饰器。
You need to have @Input for details component which can get the contact details from its component
@Component({
selector: 'app-details',
templateUrl: './details.component.html',
styleUrls: ['./details.component.css']
})
export class DetailsComponent {
@Input()
public contact;
}
List component will emit the value on selection of any items from the list.
export class ListComponent {
@Output()
public select;
public onSelect(contact){
this.select.emit(contact);
}
}
School and College component can get the the emitted value from the List Component and pass it to details component .
<div class="header">
<h3>SCHOOL</h3>
<div class="left">
<app-list [contacts]="contacts" ></app-list>
</div>
<div class="right">
<app-details></app-details>
</div>
</div>
这是工作副本 - https://stackblitz.com/edit/list-examples-mine-ilxisk