Angular TypeScript: 在 ngOnInit 中给表单文本框添加 blur 事件
在 Angular TypeScript 中,可以使用以下方式在 'ngOnInit()' 函数中给表单文本框添加 'blur' 事件:
import { Component, OnInit, ViewChild, ElementRef } from '@angular/core';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent implements OnInit {
@ViewChild('myInput', { static: true })
myInput: ElementRef;
ngOnInit() {
// 获取 input 元素
const inputEl = this.myInput.nativeElement;
// 给 input 元素添加 blur 事件
inputEl.addEventListener('blur', (event: Event) => {
console.log('Input blurred!');
});
}
}
在上面的示例中,我们通过 '@ViewChild' 装饰器获取了模板中的 'input' 元素,并在 'ngOnInit()' 函数中给它添加了 'blur' 事件监听器。当 'input' 元素失去焦点时,控制台将输出 'Input blurred!'。
原文地址: https://www.cveoy.top/t/topic/oD56 著作权归作者所有。请勿转载和采集!