问题
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>`
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.
Question: is there another proper way to communicate between the custom elemenents with Angular elements ?
回答1:
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"}
})
}
}
回答2:
Event emitters help with communication between parent - sibling.
Document: https://angular.io/api/core/EventEmitter
Observers help with the communication between elements everywhere. However you should import the observable in the component you emit and in the component that subscribes.
Document: https://angular.io/guide/observables
Try to avoid vanilla javascript for selecting elements. JS logic is fine, but all the DOM manipulations should be handled by angular, not written by hand. This after all is the purpose of frameworks such as Angular
来源:https://stackoverflow.com/questions/57324086/communication-between-two-custom-angular-elements