我试图在一个组件中单击一个按钮,将焦点放在另一个组件上的元素上。 (坦率地说,我不明白为什么它必须如此复杂,但我无法实现任何实际工作的简单方法。)
我正在使用一项服务。它不需要传递任何数据,除了 那 发生了点击。我不确定听力组件是如何响应事件的。
app.component:
跳到主要内容
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 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("!")
// should put focus() on input
);
}
}
跳跃到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();
};
}
关于登录将如何“听到”skipClicked事件,我在这里有点迷失。