Angular 2 中 onClick 事件的概念

Muhammad Adil 2023年1月30日
  1. Angular 2 onClick 事件
  2. 在 Angular 2 中创建 onClick 事件的简单步骤
  3. Angular 2 onClick 事件的示例
Angular 2 中 onClick 事件的概念

Angular 2 框架是用于构建应用程序前端的结构框架。

Angular 2 具有许多新功能,使其比其前身更加用户友好。

一个特性是能够在 Angular 2 中的 onClick 事件的帮助下调用函数。

Angular 2 onClick 事件

Angular 2 事件系统可用于处理不同类型的事件,例如鼠标点击、键盘按下和触摸手势。

onclick 事件在用户单击组件或元素时触发事件或函数。

<button (click)="define()">Define</button>

define() 语句执行组件的 define() 方法,(click) 绑定按钮单击事件。

在 Angular 2 中创建 onClick 事件的简单步骤

我们需要执行以下步骤。

  • Angular 应用程序创建一个 HTML 模板。
  • 在模板中添加一个按钮
  • 在按钮的指令中定义点击事件处理程序
  • 处理应用模块控制器中的点击事件,并在用户点击按钮时相应地更新 view-model 数据。
  • 实现视图模型数据的更新以在用户单击按钮时刷新视图。
  • 添加指令以在用户单击按钮时更新输入字段。

Angular 2 onClick 事件的示例

首先,让我们编写 Html 代码。

<button class="clickBtn" (click)="show=!show" >Click me</button>

 <div class="Demo" *ngIf="show"> 

  <h3>you can see how things are changing by pressing Clickme button</h3>

<br/>

<h3>This is how we use the concept of OnCLick Event in Angular 2</h3>

ngif 属性定义输入,它将视图与组件或组件与视图的值联系起来。

让我们转向 Typescript 代码。

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
  selector: 'app-click',
  templateUrl: './fm.component.html',
  styleUrls: ['./fm.component.css']
})
export class MyFmComponent implements OnInit {
  registerForm: FormGroup;
  submitted:false;
  constructor() { }
  ngOnInit() {
  }
}
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app',
  templateUrl: './my.component.html',
  styleUrls: ['./my.component.css']
})

export class MyComponent implements OnInit {
show = false;
  constructor() { }
  ngOnInit() {
  }
}

最后,让我们为 app.module.ts 编写 TypeScript 代码

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { MyFmComponent } from './clickme/fm.component';
import { MyComponent } from './Event/my.component';

@NgModule({
  imports:      [ BrowserModule, FormsModule ],
  declarations: [ AppComponent, HelloComponent, MyComponent, MyFmComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

点击这里查看完整的工作代码。

作者: Muhammad Adil
Muhammad Adil avatar Muhammad Adil avatar

Muhammad Adil is a seasoned programmer and writer who has experience in various fields. He has been programming for over 5 years and have always loved the thrill of solving complex problems. He has skilled in PHP, Python, C++, Java, JavaScript, Ruby on Rails, AngularJS, ReactJS, HTML5 and CSS3. He enjoys putting his experience and knowledge into words.

Facebook