事件绑定

想要将网页的点击事件绑定到类中也很简单
首先在类中定义一个方法:

app.component.ts:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
    import { Component, OnInit } from '@angular/core';
    @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
    })
    export class AppComponent {
        title = 'SampleApp';  
        onButtonClick(){
            alert("hello world!");
        }
    }

这个方法将在运行时弹出一个对话框,显示hello world!

然后在html中写入:

app.component.html:

1
<button type="button" (click)="onButtonClick()" >Button</button>

其中click加了一个括号,内容写了onButtonClick(),意思是将button标签的click事件绑定到了onButtonClick()事件上
运行后如果点击网页上的button,效果如下:

button