以下是一个解决Angular 8中动态根据下拉菜单的值聚焦于多个输入框的示例代码:
import { Component, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
selectedOption: string;
@ViewChild('input1', { static: false }) input1: ElementRef;
@ViewChild('input2', { static: false }) input2: ElementRef;
@ViewChild('input3', { static: false }) input3: ElementRef;
focusInput() {
switch (this.selectedOption) {
case 'input1':
this.input1.nativeElement.focus();
break;
case 'input2':
this.input2.nativeElement.focus();
break;
case 'input3':
this.input3.nativeElement.focus();
break;
}
}
}
在上面的代码中,我们使用ngModel
指令将下拉菜单的值绑定到selectedOption
变量上。然后,使用*ngIf
指令根据selectedOption
的值来显示相应的输入框。最后,使用@ViewChild
装饰器来获取每个输入框的引用,并在focusInput
方法中根据selectedOption
的值聚焦于相应的输入框。
这样,选择下拉菜单中的选项时,相应的输入框将被聚焦。