Angular2 recursive component - set input autofocus

2019-08-16 02:12发布

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条回答
Rolldiameter
2楼-- · 2019-08-16 02:41

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

查看更多
登录 后发表回答