Angular2 recursive component - set input autofocus

戏子无情 提交于 2019-12-11 17:51:19

问题


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.

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


回答1:


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



来源:https://stackoverflow.com/questions/54507958/angular2-recursive-component-set-input-autofocus

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!