角度4分量目标由选择器(angular 4 component target by selector)

我正在开发基于烤面包机通知的消息系统:

http://jasonwatmore.com/post/2017/06/25/angular-2-4-alert-toaster-notifications

我的问题很简单,我想扩展功能以允许多个警报组件可以在不同模板中单独针对。

例如,根app.component.html模板将具有:

<alert root></alert>

子组件将具有:

<alert subcomponent></alert>

烤面包机教程(组件)的当前实现将针对模板内的任何警报组件实例。

如果有两个,那么当服务被调用时它们都会得到相同的消息。

理想情况下,我想在服务调用中添加另一个参数:

this.alertService.success(message,target);

I'm developing a message system, based on toaster notifications:

http://jasonwatmore.com/post/2017/06/25/angular-2-4-alert-toaster-notifications

My question is simple, I want to extend the functionality to allow multiple alert components that can be targeted individually within different templates.

For example, the root app.component.html template would have:

<alert root></alert>

A sub component would have:

<alert subcomponent></alert>

The current implementation of the toaster tutorial (component) will target any instance of the alert component within a template.

If there were two, they would both get the same message when the service is invoked.

Ideally, I want to add another parameter onto the service call:

this.alertService.success(message,target);

最满意答案

您可以在名为target的alert指令组件中使用字符串输入属性。

当alert.service触发警报时,组件仅在目标匹配时才显示:

alert.component.ts

// add this input @Input() target: string; ngOnInit() { this.alertService.getAlert().subscribe((alert: Alert) => { // add this statament if (alert.target === this.target) { this.alerts.push(alert); } }); }

alert.service.ts

/*each alert function recive an extra parameter for target, if you needed with a default value, "root" for example*/

root.component.html

<alert target='root'></alert>

other.component.ts

// calling an alert this.alertService.success( message='operation success', target='root' )

you can use an string input attribute in the alert directive component called target.

and when the alert.service trigger an alert the component only shows if the target match:

alert.component.ts

// add this input @Input() target: string; ngOnInit() { this.alertService.getAlert().subscribe((alert: Alert) => { // add this statament if (alert.target === this.target) { this.alerts.push(alert); } }); }

alert.service.ts

/*each alert function recive an extra parameter for target, if you needed with a default value, "root" for example*/

root.component.html

<alert target='root'></alert>

other.component.ts

// calling an alert this.alertService.success( message='operation success', target='root' )

更多推荐