在Angular 2中,可以使用双向数据绑定来将数字从输入中转换为字符串。
以下是一个示例解决方法:
number-to-string.component.html:
转换后的字符串: {{ convertedString }}
number-to-string.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'app-number-to-string',
templateUrl: './number-to-string.component.html',
styleUrls: ['./number-to-string.component.css']
})
export class NumberToStringComponent {
inputNumber: number;
convertedString: string;
convertToString() {
this.convertedString = this.inputNumber.toString();
}
}
app.module.ts:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { NumberToStringComponent } from './number-to-string.component';
@NgModule({
declarations: [
AppComponent,
NumberToStringComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
app.component.html:
这样,当你在输入框中输入一个数字时,Angular会自动将其转换为字符串,并在页面上显示转换后的字符串。