两个自定义(角度)元素之间的通信 [英] Communication between two custom (angular) elements

查看:69
本文介绍了两个自定义(角度)元素之间的通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

两个自定义(角度)元素之间的通信

Communication between two custom (angular) elements

假设有两个自定义元素。

Let's say there are two custom elements.

- login-button `<login-button id="loginbutton"></login-button>;`
- and status-login `<status-login></status-login>`

按下登录按钮时,元素登录按钮将发出输出事件 loginbuttonpressed
Angular元素会将输出事件转换为自定义事件。

When the login button is pressed element login-button will emit the output event loginbuttonpressed. Angular elements will transform this output event to a custom-event.

然后在状态登录中,您可以执行以下操作:

Then in the status-login you can then do like:

constructor( @Inject(DOCUMENT) document) {
    document.getElementById('loginbutton').addEventListener('loginbuttonpressed', this.loginIsPressed);
}

因此,它将在分派自定义事件时监听,这一切都很好。

So it will listen when the custom event is dispatched, this all works great.

问题:在带有Angular元素的自定义元素之间还有另一种正确的通信方式吗?

Question: is there another proper way to communicate between the custom elemenents with Angular elements ?

推荐答案

使用角度EventEmitter,在一个组件中进行发射,并通过一些通用服务订阅另一个组件。每当调用loginBtnClick()时,都会在状态组件中触发事件。这样,即使它们之间没有父子关系,也可以将数据从一个组件传递到另一个组件

Use angular EventEmitter, Emit in one component and subscribe in another component via some common service. Whenever loginBtnClick() is called event will be triggered in status component. This way you can pass data from one component to other even if they are not in parent-child relationship

import { EventEmitter } from '@angular/core';
// service
@Injectable()
export class CommonService(){
loginClicked: EventEmitter<String> = new EventEmitter<String>();
}

export class loginBtn(){
   constructor(private commonService: CommonService);

   loginBtnClick(){
      this.commonService.loginClicked.emit({data: "any data"});
   }
}

export class status(){
   constructor(private commonService: CommonService);

   ngOnInit(){
       this.commonService.loginClicked.subscribe((data) => {
           console.log(data) // {data: "any data"}
        })
   }
}

这篇关于两个自定义(角度)元素之间的通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆