如何使用Angular 8使输入出现基于打字的句子情况
在这个例子中,我们将看到如何使用angular8使输入出现基于键入的句子大小写。
步骤:
- 首先,我们需要为HTML文件中的输入类型编写代码。
- 在HTML中把输入类型写成文本后,使用双向绑定,即使用ngModel,我们可以绑定输入域的值。
- 现在,为了使输入字段的句子情况,我们可以使用ngModelChange事件来根据要求操纵值。
- 确保你从’@angular/forms’导入了’FormsModule’。
- 导入模块后,现在我们需要在ts文件中实现这个功能,我们可以根据要求使用regex修改输入值,如句子的大小写,并可以显示在输入栏中。
- 上述步骤完成后,启动,或为项目的运行服务。
代码实现:
app.component.ts:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
inputvalue = ''
changeToSentenceCase(event) {
this.inputvalue = event.replace(/\b\w/g,
event => event.toLocaleUpperCase());
}
}
app.component.html:
<p>Type in textbox to make as sentence case.</p>
<input type='text' [(ngModel)]="inputvalue"
(ngModelChange)="changeToSentenceCase($event)">
app.module.ts:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
imports: [BrowserModule, FormsModule],
declarations: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule { }
输出: