我在 Angular 中显示 maxlength 属性的错误消息时遇到一些问题。
Problem
由于 maxlength 属性不允许的字符数超过指定数量,因此我无法显示错误消息。有什么方法可以关闭默认行为(允许用户输入更多字符),以显示我的错误消息。
文本区域的代码
<textarea maxlength="10"
[(ngModel)]="title.value"
#title="ngModel"></textarea>
角度验证代码
<div *ngIf="title.errors && (title.dirty || title.touched)"
class="alert alert-danger">
<div [hidden]="!title.errors.maxlength">
Only 10 characters allowed.
</div>
</div>
如果您希望我提供任何其他信息,请告诉我。
您可以使用反应式表单来正确验证您的表单,
这是一个如何使用反应式表单的简单示例:
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)]],
});
}
}
希望对你有帮助:)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)