我最近问了一个有关如何将自定义验证指令的输出显示到另一个表单元素中的问题,并收到了一个答案,然后我可能很快就将其选为“答案”,因为我现在正在尝试建议的方法,并且出现控制台错误:"_co.myInput is undefined"
我想将自定义验证指令的输出消息显示到表单上的另一个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>
“答案”如下:
<input #myInput="ngModel" name="{{key}}" . . . >
. . .
<p>{{myInput.errors.hasSpecialChars?.message}}</p>
我是否需要修改hasSpecialChars指令?还是我需要解决另一个问题?