如何在自定义组件中访问表单验证 angular 4

How can I access form validation in custom component angular 4

我的表单有一个自定义组件:app-form

@Component({
  selector: "app-form",
  template: `
  <form (ngSubmit)="onSubmit()">
      <div class="row">
        <ng-content></ng-content>
      </div>
      <button type="submit">Save</button>
  </form>
  `,
  animations,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: FormComponent,
      multi: true
    }
  ]
})

并且我有一个用于输入的自定义组件:app-form-text

@Component({
  selector: "app-form-text",
  template: `
  <div class="form-group"
      [class.has-success]="nameval.valid && (nameval.dirty || nameval.touched)"
      [class.has-danger]="nameval.invalid && (nameval.dirty || nameval.touched)">
      
      <input type="text" class="form-control"
        [class.form-control-success]="nameval.valid"
        [class.form-control-danger]="nameval.invalid && nameval.dirty"
        #nameval="ngModel" [name]="nameval"  maxlength="250" minlength="2" [(ngModel)]="value"
        required [appNmsValidators]='ValidationType'>
        <div *ngIf="nameval.errors && (nameval.dirty || nameval.touched)">
          <p *ngIf="nameval.errors.required">{{ReqErMsg}}</p>
          <p *ngIf="nameval.errors.minlength">{{MinErMsg}}</p>
          <p *ngIf="nameval.errors.appNmsValidators">{{Cu1ErMsg}}</p>
        </div>
      <small class="form-text text-muted"></small>
  </div>
  `,
  animations,
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: FormTextComponent,
      multi: true
    }
  ]
})

我使用它们如下:

<app-form [FormName]="'BaseCodeForm'">
    <div class="col-md-6">
      <app-form-text required name="typeCode"   
        [(ngModel)]="BaseCodeModel.typeCode">
      </app-form-text>
    </div>
    <div class="col-md-6">
      <app-form-text required name="descCode" 
        [(ngModel)]="BaseCodeModel.descCode">
      </app-form-text>
    </div>
  </app-form>

如何在应用程序表单组件中访问表单验证?

在应用程序表单组件中,您应该尝试使用@ViewChild

注入 NgForm 实例
@ViewChild(NgForm) form: NgForm;

它应该可以在 ngOnInit() 方法中访问