Angularを使って、htmlのtextareaに入力可能な残り文字数を表示させるサンプルプログラムです。
残りの入力文字数が少なくなってきたら赤文字にして警告し、文字数オーバーしたら太字で強調します。
プログラム
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `
<form #inquiryForm="ngForm" (ngSubmit)="submit()" novalidate>
<textarea cols="50" rows="6" name="msg"
[(ngModel)]="message"
(input)="inputText()"></textarea>
<br />
<div [ngStyle]="alertStyle">
残り{{restCount}}文字入力できます
</div>
<input type="submit" name="submit" [disabled]="inquiryForm.invalid" >
</form>
`,
})
export class AppComponent {
message = "";
maxCount = 100;
restCount = this.maxCount;
alertStyle = {};
// TextAreaにテキストが入力されたときのハンドラ
inputText() {
this.restCount = this.maxCount - this.message.length;
// 残りの入力文字数に応じて警告を出す
if ( this.restCount > 30 ) {
// 余裕がある場合
this.alertStyle = {color: '#000', fontWeight: 'normal'};
} else if ( this.restCount > 0 ) {
// もう少しで上限に達する時
this.alertStyle = {color: '#f33', fontWeight: 'normal'};
} else {
// 上限オーバーしたとき(何文字オーバーしているかを表示)
this.alertStyle = {color: '#f00', fontWeight: 'bold'};
}
}
}
実行結果
余裕がある場合
もう少しで上限に達する時
上限オーバーしたとき(何文字オーバーしているかを表示)
こちらもおススメ