繁体   English   中英

从 Angular 中的父组件设置焦点到子组件文本框

[英]Set focus on Child component textbox from Parent component in Angular

我正在尝试将焦点设置在 Angular 中父组件的子组件文本框上。

父组件 HTML

<button (click)="setFocusOnChildComponentTextBox()">Button</button>
<child-component></child-component>

子组件 HTML

<input type="text" id="txt" name="txt"></input>

父组件 TS

setFocusOnChildComponentTextBox() {
// write code to set focus on child-component "txt" textbox
}

以上只是我试图实现的示例代码。

通常在 Angular 中,我们可以将输入属性传递给子组件并具有 output 方法。 在这种情况下,我需要从父组件调用子组件的方法。

在子组件中假设您有输入

<input type="text" #myInput></input>

在子组件 typescript 有

@ViewChild('myInput', {read:ElementRef}) myInput: ElementRef<HTMLInputElement>;

在父组件 typescript 中有

@ViewChild(ChildComponent) comp: ChildComponent;

集中使用

this.comp.myInput.nativeElement.focus();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM