Angular blur 事件
Rana Hasnain Khan
2024年2月15日
Angular
Angular Blur
本文將通過示例介紹 Angular 中的 blur 事件。
Angular 中的模糊 blur
在很多情況下,我們可能需要在 Angular 中使用 blur 事件。例如,對於驗證欄位,我們可能希望在某個欄位失去焦點時驗證該欄位。
Angular 為這種情況提供了 blur 事件。
blur 事件在元素失去焦點時觸發。Angular 中 blur 事件的語法如下所示。
<input (blur)='DoSomething()'/>
讓我們使用以下命令在 Angular 中建立一個新應用程式。
ng new my-app
在 Angular 中建立我們的新應用程式後,我們將使用這個命令進入我們的應用程式目錄。
cd my-app
現在,讓我們執行我們的應用程式來檢查所有依賴項是否安裝正確。
ng serve --open
在 app.component.ts 中,我們將建立一個在 blur 事件上觸發的函式,如下所示。
import { Component } from '@angular/core';
type Fruit = Array<{ id: number; name: string }>;
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {
blurEvent(): void {
console.log('Blur event Activated!');
}
}
在 app.component.html 中,我們將建立一個 input 元素並設定一個 blur 事件,如下所示。
<label>Enter Name:</label>
<input type="text" placeholder="Enter name.." (blur)="blurEvent()">
現在,讓我們通過執行以下命令來服務 Angular 應用程式。
ng serve
輸出:

上面的示例顯示,只要輸入失去聚焦,就會啟用 blur 事件。
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.
LinkedIn