ListKeyManager
管理组件元素和键盘的互动
要使用ListKeyManager功能有3個步驟:
- 使用
@ViewChildren查出页面上需要包含在內的元件 - 建立一个新的
ListKeyManager,并把上一步查出來的原价清单传入 - 使用相关的键盘事件及设定状态的方法,來达到互动效果。
使用FocusKeyManager
下面是一个利用键盘循环选中input框的🌰:
建一个通用的directive, 来获取包含focus方法的原件.
FocusableOption继承自ListKeyManagerOption, 必须包含focus方法
1
2
3
4
5
6
7
8
9
10
11
12
13import {Directive, ElementRef} from '@angular/core';
import {FocusableOption} from '@angular/cdk/a11y';
({
selector: '[appSurveyInput]'
})
export class SurveyInputDirective implements FocusableOption {
constructor(private element: ElementRef) {}
focus() {
this.element.nativeElement.focus();
}
}给需要被轮训选中的input框加入appSurveyInput
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22<div class="main">
<p>
<label>姓名</label>
<input appSurveyInput>
</p>
<p>
<label>电话</label>
<input appSurveyInput>
</p>
<p>
<label>邮箱</label>
<input appSurveyInput>
</p>
<p>
<label>公司</label>
<input appSurveyInput>
</p>
<p>
<label></label>
<button app-ics-button>保存</button>
</p>
</div>获取元素, 初始化并实现选中功能
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26// 取得所有 SurveyInputDirective 的元素
(SurveyInputDirective) surveyInputs: QueryList<SurveyInputDirective>;
keyManager: FocusKeyManager<SurveyInputDirective>;
// 监听所有 keydown 事件
('keydown', ['$event'])
keydown($event: KeyboardEvent) {
// 当 按下UP_ARROW建时focus上一个input
if ($event.keyCode === UP_ARROW) {
this.keyManager.setPreviousItemActive();
} else if ($event.keyCode === DOWN_ARROW) {
// 当 按下DOWN_ARROW建时focus下一个input
this.keyManager.setNextItemActive();
}
}
ngOnInit() {
}
ngAfterViewInit() {
// 新建一个FocusKeyManager, 用于实现选中功能. .withWrap(): 让surveyInputs形成一个循环
this.keyManager = new FocusKeyManager(this.surveyInputs).withWrap();
// 默认选中第一个input
this.keyManager.setActiveItem(0);
}
Bidirectionality
控制排列方式
Layout
用于检测浏览器的大小
引入 LayoutModule
BreakpointObserver
1 | export class DashboardComponent implements OnInit { |
Observables
引入ObserversModule