Angular 2 の onClick イベントの概念
Angular 2 フレームワークは、アプリケーションのフロントエンドを構築するための構造的なフレームワークです。
Angular 2 には、以前のバージョンよりもユーザーフレンドリーにする多くの新機能があります。
1つの機能は、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 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