[英]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.