gpt4 book ai didi

javascript - Renderer2 错误 - id 与任何元素都不匹配

转载 作者:行者123 更新时间:2023-12-02 19:26:58 24 4
gpt4 key购买 nike

所以我有一个输入字段,我想专注于 Angular 应用程序中的加载。我读到 Renderer2 方式是这样做的好方法,如果我像这样在单击时调用该函数,它就可以工作:

focusMyInput() {
this.renderer.selectRootElement('#myInput').focus();
}

但是如果我尝试让它专注于负载,如下所示:

ngAfterViewInit() {
this.renderer.selectRootElement('#myInput').focus();
}

它抛出一个错误:

 The selector "#myInput" did not match any elements
at DefaultDomRenderer2.selectRootElement

HTML:

<input id="myInput" />

知道这背后的原因是什么吗?

最佳答案

请尝试这个workig demo

 @ViewChild('myInput') myInput: ElementRef;//if it is direct child or element
@ContentChild('myInput') myInput: ElementRef;// if it is inside ng-content html

ngAfterViewInit() {
this.renderer.selectRootElement(this.myInput.nativeElement).focus();
}

or

 ngAfterContentInit() {
this.renderer.selectRootElement(this.myInput.nativeElement).focus();
}

in Html you have to do like

<input id="myInput" #myInput />

关于javascript - Renderer2 错误 - id 与任何元素都不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62298616/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com