I am trying to get a button click in one component to focus on an element on another component. (Honestly, I don’t understand why it should be so complicated, but I could not implement any simpler way that really works.)
I use the service. He does not need to transfer any data except that a click has occurred. I'm not sure how the listening component should respond to the event.
app.component:
Skip to main content
import { Component } from '@angular/core';
import { SkipToContentService } from './services/skip-to-content.service';
export class AppComponent {
constructor(
private skipToContent: SkipToContentService
) {}
}
skipLink() {
this.skipToContent.setClicked();
}
}
input component:
<input type="text" name="username" />
import { Component, OnInit } from '@angular/core';
import { SkipToContentService } from '../../../services/skip-to-content.service';
export class BaseLoginComponent implements OnInit {
constructor(
private skipToContent: SkipToContentService
) {
}
ngOnInit() {
this.skipToContent.skipClicked.subscribe(
console.log("!")
);
}
}
pass to content.service:
import { Injectable, EventEmitter } from '@angular/core';
@Injectable()
export class SkipToContentService {
skipClicked: EventEmitter<boolean> = new EventEmitter();
constructor() {
}
setClicked() {
console.log('clicked');
this.skipClicked.emit();
};
}
I lost a little here, as the login will “hear” the skipClicked event.
source
share