我的表单有自定义组件: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
}
]
})
&#13;
我的输入有一个自定义组件: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
}
]
})
&#13;
我使用它们如下:
<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>
&#13;
如何在app-form组件中访问表单验证?
答案 0 :(得分:1)
在app-form组件中,你应该尝试使用@ViewChild注入NgForm实例
@ViewChild(NgForm) form: NgForm;
应该可以在ngOnInit()方法中访问它