以下是一个使用Angular和TypeScript的示例代码,用于在点击按钮时使用构造函数更改数字:
{{ number }}
import { Component } from '@angular/core';
@Component({
selector: 'app-example',
templateUrl: './example.component.html',
styleUrls: ['./example.component.css']
})
export class ExampleComponent {
number: number;
constructor() {
this.number = 0;
}
changeNumber() {
this.number += 1;
}
}
在构造函数中,我们将数字初始化为0。当点击按钮时,changeNumber()
方法会将数字加1。
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { ExampleComponent } from './example.component';
@NgModule({
declarations: [
AppComponent,
ExampleComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
这样,当点击按钮时,数字将逐渐增加并在页面上显示。