如何检测由于 Angular 中的 *ngIf 而尚未出现在视图中的子视图?

问题描述 投票:0回答:1

我有一个使用

*ngIf
隐藏的输入。我不想按照相关问题中的建议进行更改。当我单击组件时,输入需要不到一秒钟的时间才能进入视图。这是如此轻微的延迟,性能和感知都受到影响,所以我通过设置计时器来解决它。

@ViewChild("input") input: ElementRef;
@HostListener("click") onClick() {
  this.config.editing = true;
  timer(10).subscribe(a => this.input.nativeElement.focus());
}

尽管如此,它还是让我在主要层面上感到烦恼,因为它的设计很糟糕。务实。但很穷。所以我想知道是否有另一种方法可以在输入进入网页后立即设置焦点。

html angular
1个回答
0
投票

您可以使用 Angular 组件生命周期 来协调父/子关系之间采取的操作。

以下是如何完成此操作的快速示例:

parent.html

<child-component #input (initialized)="focusOnInput()"></child-component>

parent.ts

@ViewChild("input") input: ChildComponent;
@HostListener("click") onClick() {
  this.config.editing = true;
  // Will display our input, which then will trigger focus
}

focusOnInput() {
  this.input.focus()
}

child.html

<input ... #input />

child.ts

class ChildComponent implemenets AfterViewInit {
  @ViewChild('input') input: ElementRef;
  @Output initialized: EventEmitter<void> = new EventEmitter()

  ngAfterViewInit() {
    this.initialized.emit()
  }

  focus() {
    this.input.nativeElement.focus()
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.