Angular 8中的事件绑定

Angular 8中的事件绑定

在Angular 8中,事件绑定被用来处理由用户行为引发的事件,如点击按钮、鼠标移动、击键等。当DOM事件发生在一个元素上时(如点击、按键、上键),它会调用特定组件中的指定方法。

使用事件绑定,我们可以将数据从DOM绑定到组件上,从而可以将这些数据用于其他目的。

语法:

< element (event) = function() >

步骤:

  • 在app.component.ts文件中定义一个函数,它将完成给定的任务。
  • 在app.component.html文件中,将该函数与HTML元素上的给定事件绑定。

例子1:在输入元素上使用点击事件。

app.component.html

<h1>
  GeeksforGeeks
</h1>
<input (click)="gfg($event)" value="Geeks">

app.component.ts

import { Component } from '@angular/core';    
@Component({    
  selector: 'app-root',    
  templateUrl: './app.component.html',    
  styleUrls: ['./app.component.css']    
})    
export class AppComponent {    
  gfg(event) {
    console.log(event.toElement.value);
  }    
}

输出:

Angular 8中的事件绑定

实例2:在输入元素上使用keyup事件。

app.component.html

<!-- event is passed to function -->
<input (keyup)="onKeyUp($event)">  
  
  
<p>{{text}}</p>

app.component.ts

import { Component } from '@angular/core';    
@Component({    
  selector: 'app-root',    
  templateUrl: './app.component.html',    
  styleUrls: ['./app.component.css']    
})    
export class AppComponent {   
  text = ''; 
  onKeyUp(x) { 
  
    // Appending the updated value
    // to the variable 
    this.text += x.target.value + ' | '; 
  } 
}

输出:

Angular 8中的事件绑定

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程