在Angular中,可以使用ViewChild
装饰器和ElementRef
类来在组件中唯一识别HTML表单控件。以下是一个示例:
HTML模板:
组件代码:
import { Component, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
@ViewChild('usernameInput') usernameInput: ElementRef;
@ViewChild('passwordInput') passwordInput: ElementRef;
ngAfterViewInit() {
console.log(this.usernameInput.nativeElement);
console.log(this.passwordInput.nativeElement);
}
}
在上面的代码中,我们使用ViewChild
装饰器和ElementRef
类来获取HTML表单控件的引用。ViewChild
装饰器接受一个参数,该参数是HTML模板中的#
引用变量的名称。在ngAfterViewInit
生命周期钩子函数中,我们可以访问nativeElement
属性来获取控件的原生DOM元素。
通过这种方式,我们可以在组件中唯一识别和操作HTML表单控件。