【问题标题】:angular 4 component target by selector选择器的角度 4 组件目标
【发布时间】:2018-05-09 21:06:05
【问题描述】:

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

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);

【问题讨论】:

  • 如果您可以将答案标记为已接受,请告知

标签: angular typescript components alert messaging


【解决方案1】:

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

当 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'
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-10
    • 2020-09-10
    • 2019-01-23
    • 2016-03-13
    相关资源
    最近更新 更多