可以使用ViewChild
和ElementRef
来实现设置多个聚焦输入元素的类或样式。
首先,在组件中引入ViewChild
和ElementRef
:
import { Component, ElementRef, ViewChild } from '@angular/core';
然后,在组件类中使用@ViewChild
装饰器来获取聚焦输入元素的引用:
@Component({
selector: 'app-root',
template: `
`
})
export class AppComponent {
@ViewChild('input1', { static: true }) input1: ElementRef;
@ViewChild('input2', { static: true }) input2: ElementRef;
// 其他组件代码
}
在模板中,我们使用#input1
和#input2
来定义输入元素的引用。然后,我们使用@ViewChild
装饰器将这些引用赋值给组件类中的input1
和input2
属性。
接下来,我们可以在组件类中使用ngAfterViewInit
生命周期钩子来设置聚焦输入元素的类或样式:
export class AppComponent {
// 其他组件代码
ngAfterViewInit() {
this.input1.nativeElement.classList.add('focused');
this.input2.nativeElement.style.border = '2px solid red';
}
}
在ngAfterViewInit
生命周期钩子中,我们可以获取聚焦输入元素的原生DOM元素,并使用classList
属性来添加或删除类,使用style
属性来设置样式。
最后,我们可以在CSS中定义所需的类或样式:
.focused {
background-color: yellow;
}
/* 其他样式 */
这样,当组件加载后,input1
元素将会添加focused
类,input2
元素将会添加红色的边框样式。