【发布时间】:2016-11-07 17:00:41
【问题描述】:
实现迭代error-text-accumulation pattern from the angular2 documentation,我将自定义表单验证器中的所有消息汇总到一个字符串中以显示给用户:
onValueChanged(data?: any) {
if (!this.heroForm) { return; }
const form = this.heroForm.form;
for (const field in this.formErrors) {
// clear previous error message (if any)
this.formErrors[field] = '';
const control = form.get(field);
if (control && control.dirty && !control.valid) {
const messages = this.validationMessages[field];
for (const key in control.errors) {
this.formErrors[field] += messages[key] + '\n';
}
}
}
}
我们的设计要求这些在没有任何列表修饰的情况下显示为输入字段下方的多行文本。
使用上面的函数,并在右大括号之前记录,我看到了我期望我的字符串包含的内容:
password1: "Must contain an uppercase character.↵Must contain a special character.↵Must contain a numeric character.↵
但是,当它到达模板时,它变成了这样:
<div _ngcontent-xoo-4="" class="error-message-field">
Must contain an uppercase character.
Must contain a special character.
Must contain a numeric character.
</div>
因为我正在使用
.error-message-field {
height: auto;
white-space: pre-line;
}
我的字段错误上方和下方多了一行。
这两个额外的\n 来自哪里?我自己不会在其他任何地方操作生成的字符串。
【问题讨论】:
标签: angular angular2-template angular2-forms