问题描述
我正在创建一个类似于工作流的树形视图(主要用于实践),这个简单的版本正在工作,但是我不知道添加新组件时如何设置输入焦点.
I'm creating a tree view similar to workflowy (for practice mostly), and this simple version is working but I can't figure out how to set the input focus when a new component is added.
我尝试在输入上添加autofocus属性,并使用ViewChild在ngAfterViewInit之后设置焦点.在添加第一个组件时似乎起作用了,但是此后却没有.
I've tried adding the autofocus property on the input and using ViewChild to set focus after ngAfterViewInit. It seems to work when adding the first component but not thereafter.
这里是一次闪电战,以显示我所在的位置:
Here is a stackblitz to show where i'm at:
https://stackblitz.com/edit/angular-input-autofocus
推荐答案
在最近创建的组件中实现自动对焦"的简便方法是使用ViewChildren
the easer way to "autofocus" in a recently component created is using ViewChildren
@ViewChildren() items!: QueryList<ElementRef>;
ngAfterViewInit() {
this.items.changes.subscribe((r) => {
//If you want to focus to first
this.items.first().nativeElement.focus();
//or if you want to focus to last
this.items.last().nativeElement.focus();
}
但是,看到您的堆叠爆炸,我无法想象您想做什么
But, seeing your stackblitz, I can not imagine what you want to do
这篇关于Angular2递归组件-设置输入自动对焦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!