Mat*_*erg 8 forms validation textarea maxlength angular
我在Angular中显示maxlength属性的错误消息时遇到了一些麻烦.
问题
由于maxlength属性不允许多于指定数量的字符,因此我无法显示错误消息.有没有办法打开默认行为(允许用户键入更多字符),以显示我的错误消息.
textarea的代码
<textarea maxlength="10"
[(ngModel)]="title.value"
#title="ngModel"></textarea>
Run Code Online (Sandbox Code Playgroud)
角度验证代码
<div *ngIf="title.errors && (title.dirty || title.touched)"
class="alert alert-danger">
<div [hidden]="!title.errors.maxlength">
Only 10 characters allowed.
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
如果您希望我提供任何其他信息,请告诉我.
您可以通过直接在输入长度上设置条件来实现。带* ngIf的span标记可以显示/隐藏错误消息:
的HTML
<textarea class="form-control" id="title" maxlength="10"
type="number" name="title" [(ngModel)]="titleModel"></textarea>
<span style="color:red" *ngIf="titleModel?.length > 10">
10 max
</span>
Run Code Online (Sandbox Code Playgroud)
类:...
titleModel = 'I have more than 10 characters'
Run Code Online (Sandbox Code Playgroud)
... 演示
您可以使用反应式表单来正确验证您的表单,这是一个简单的示例,说明如何使用反应式:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'title-form',
template: `
<form novalidate [formGroup]="myForm">
<label>
<span>Full title</span>
<input type="text" placeholder="title.." formControlName="title">
</label>
<div*ngIf="myForm.controls['title'].touched && myForm.get('title').hasError('required')">
Name is required
</div>
<div *ngIf="myForm.controls['title'].touched && myForm.controls['title'].hasError('maxlength')">
Maximum of 10 characters
</div>
</form>
`
})
export class TitleFormComponent implements OnInit {
myForm: FormGroup;
constructor(private fb: FormBuilder) {}
ngOnInit() {
this.myForm = this.fb.group({
title: ['', [Validators.required, Validators.maxLength(10)]],
});
}
}
Run Code Online (Sandbox Code Playgroud)
希望对你有帮助:)