在Angular 2+中,可以使用ViewChild
和ElementRef
来聚焦到上一个元素。下面是一个示例代码:
app.component.html:
app.component.ts:
import { Component, ElementRef, ViewChild } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
@ViewChild('input1') input1: ElementRef;
@ViewChild('input2') input2: ElementRef;
focusPreviousElement(currentElement: ElementRef) {
if (currentElement.nativeElement === this.input2.nativeElement) {
this.input1.nativeElement.focus();
}
}
}
在上面的示例中,我们使用ViewChild
装饰器来获取输入元素的引用,并使用ElementRef
来访问元素的原生DOM对象。然后,我们定义了一个focusPreviousElement
方法,该方法接受当前元素作为参数。在这个方法中,我们检查当前元素是否为第二个输入元素,如果是,则聚焦到第一个输入元素。
请注意,这只是一个简单的示例,您可以根据实际需求进行调整和扩展。