显示来自另一个HTML元素中一个元素的自定义指令的结果

时间:2019-03-08 21:34:43

标签: angular

我想将自定义验证指令的输出消息显示到表单上的另一个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>

2 个答案:

答案 0 :(得分:2)

您可以访问以下表单验证错误:

git-search.component.html

....
<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)

您的指令可以将消息设置为共享服务,然后您可以从任何组件访问消息。