Angular ngOnInit() 中添加表單 blur 事件示例 - TypeScript
以下是一個 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('myForm') myForm: ElementRef;
ngOnInit(): void {
const formElement = this.myForm.nativeElement;
const inputElements = formElement.querySelectorAll('input');
inputElements.forEach(input => {
input.addEventListener('blur', () => {
console.log('Input blurred:', input.value);
});
});
}
}
在這個例子中,我們使用了 Angular 的 ViewChild 裝飾器,來獲取模板中的表單元素。然後,使用原生 DOM 操作,找到表單中的所有 input 元素,並為它們添加 blur 事件監聽器。當輸入框失去焦點時,就會觸發這個事件,並執行 console.log() 函數。
原文地址: https://www.cveoy.top/t/topic/oD6j 著作权归作者所有。请勿转载和采集!