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