我想将自定义验证指令的输出消息显示到表单上的另一个HTML元素中。如何捕获/引用自定义指令(no-special-chars.directive.ts
)的输出?
指令(no-special-chars.directive.ts
)
import { Directive } from '@angular/core';
import { Validator,
FormControl,
NG_VALIDATORS,
ValidationErrors} from "@angular/forms";
@Directive({
selector: '[appNoSpecialChars]',
providers: [{provide: NG_VALIDATORS, useExisting: NoSpecialCharsDirective, multi: true}],
exportAs: 'noSpecChars'
})
export class NoSpecialCharsDirective implements Validator{
constructor() { }
validate(c: FormControl): ValidationErrors {
//console.log("input value: " + c.value);
const hasSpecialChars = /[~!@#\^&*+=\-\[\]\';,/{}|\":<>\?\\()]/.test(c.value);
const message = {
'hasSpecialChars' : {
'message': 'No Special Chars Allowed'
}
};
return hasSpecialChars ? message : null;
}
}
这是模板:(git-search.component.html)
<h3>{{title}} - {{displayQuery}} -- (version: Template Driven)</h3>
<form #myForm="ngForm" (ngSubmit)="sendQuery()">
<div *ngFor="let key of modelKeys">
{{key}}
<input #myInput name="{{key}}" placeholder="Enter {{key}} Here" [(ngModel)]="model[key]" required *ngIf="key==='q'" appNoSpecialChars/>
<input #myInput name="{{key}}" placeholder="Enter {{key}} Here" [(ngModel)]="model[key]" minlength = '2' maxlength='4' *ngIf="key==='stars'" appNoSpecialChars />
<input #myInput name="{{key}}" placeholder="Enter {{key}} Here" [(ngModel)]="model[key]" *ngIf="key!=='q' && key!=='stars'" appNoSpecialChars/>
<!-- WANT TO DISPLAY MESSAGE FROM THE appNoSpecialChars DIRECTIVE INTO INNER HTML OF <p> ELEMENT BELOW: -->
<p>MESSAGE TEXT FROM DIRECTIVE</p>
</div>
<button type="submit" [disabled]="!myForm.valid">Submit</button>
</form>
答案 0 :(得分:2)
您可以访问以下表单验证错误:
....
<input #myInput="ngModel" name="{{key}}" placeholder="Enter {{key}} Here" [(ngModel)]="model[key]" required *ngIf="key==='q'" appNoSpecialChars/>
....
<p>MESSAGE TEXT FROM DIRECTIVE: {{myInput.errors.hasSpecialChars?.message}}</p>
....
因此,您需要获取对ngModel
格式的引用,在这种情况下,我们将其存储在myInput
变量中,验证程序将仅将特殊错误添加到此字段的errors
字段中宾语。
希望有帮助。
答案 1 :(得分:1)
您的指令可以将消息设置为共享服务,然后您可以从任何组件访问消息。