📅  最后修改于: 2020-10-27 02:30:03             🧑  作者: Mango
在本章中,我们将讨论事件绑定在Angular 7中的工作方式。当用户以键盘移动,鼠标单击或鼠标悬停的形式与应用程序交互时,它将生成一个事件。需要处理这些事件以执行某种操作。这是事件绑定出现的地方。
让我们考虑一个例子,以更好地理解这一点。
app.component.html
Welcome to {{title}}.
Months :
Condition is valid.
Condition is valid
Condition is invalid
在app.component.html文件中,我们定义了一个按钮,并使用click事件向其中添加了一个函数。
以下是定义按钮并为其添加函数的语法。
(click) = "myClickFunction($event)"
该函数在以下位置定义: app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular 7';
// declared array of months.
months = ["January", "February", "March", "April", "May","June", "July",
"August", "September", "October", "November", "December"];
isavailable = true; //variable is set to true
myClickFunction(event) {
//just added console.log which will display the event details in browser on click of the button.
alert("Button is clicked");
console.log(event);
}
}
单击按钮后,控件将转到函数myClickFunction ,将出现一个对话框,该对话框显示单击了Button ,如以下屏幕截图所示-
按钮的样式添加在add.component.css中-
button {
background-color: #2B3BCF;
border: none;
color: white;
padding: 10px 10px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 20px;
}
现在让我们将onchange事件添加到下拉列表中。
以下代码行将帮助您将change事件添加到下拉列表中-
app.component.html
Welcome to {{title}}.
Months :
Condition is valid.
Condition is valid
Condition is invalid
该函数在app.component.ts文件中声明-
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular 7';
// declared array of months.
months = ["January", "Feburary", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"];
isavailable = true; //variable is set to true
myClickFunction(event) {
//just added console.log which will display the event
details in browser on click of the button.
alert("Button is clicked");
console.log(event);
}
changemonths(event) {
console.log("Changed month from the Dropdown");
console.log(event);
}
}
从下拉列表中选择月份,您会看到控制台消息“事件从下拉列表中更改了月份”以及事件。
当下拉菜单中的值更改时,让我们在app.component.ts中添加警报消息,如下所示-
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular 7';
// declared array of months.
months = ["January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"];
isavailable = true; //variable is set to true
myClickFunction(event) {
//just added console.log which will display the event
details in browser on click of the button.
alert("Button is clicked"); console.log(event);
}
changemonths(event) {
alert("Changed month from the Dropdown");
}
}
更改下拉列表中的值时,将出现一个对话框,并显示以下消息:
“从下拉菜单更改月份”。