可以通过在matInput上绑定ngModel,使用Angular中的pipe或directive来进行格式化。
示例代码:
在HTML中:
在Component中:
// 定义一个数字类型的变量
myNumberValue: number = 123.456;
// 在NgModule中导入FormsModule
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
这里使用了number pipe来格式化数字,控制小数点后保留的位数。
在HTML中:
在Directive中:
// 导入Directive
import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
selector: '[appMyFormat]'
})
export class MyFormatDirective {
constructor(private el: ElementRef) { }
@HostListener('blur') onBlur() {
let val = this.el.nativeElement.value;
val = val.toUpperCase();
this.el.nativeElement.value = val;
}
}
这里使用了directive来监听input的blur事件,实现了将输入的小写字母转换为大写字母的功能。
注意,在NgModule中需要声明这个Directive:
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent, MyFormatDirective ],
bootstrap: [ AppComponent ]
})
export class AppModule { }