我有一种使用html之类的指令的形式
<form novalidate #form="ngForm" (ngSubmit)="updateListing(form)" [ngClass]="{'was-validated': isSubmitted}">
<div class="row">
<div class="col-sm-12">
<h2>Seller Information</h2>
</div>
</div>
<div class="card-box">
<listing-seller [listingSeller]="listingSeller" [listingForm]="form"></listing-seller>
<div class="col-sm-12">
<div class="form-group">
<label for="Seller_InsideCityLimits"> Inside city limits</label>
<label>
<input type="radio" [value]="true" [(ngModel)]="listingSeller.insideCityLimits" name="InsideCityLimits"> Yes
</label>
<label>
<input type="radio" [value]="false" [(ngModel)]="listingSeller.insideCityLimits" name="InsideCityLimits"> No
</label>
{{listingEditModel.sellers.insideCityLimits}}
</div>
</div>
</div>
组件具有
@ViewChild('form') form: NgForm
在我的卖家列表指令中,我有一个名为Legalname的字段
<div class="form-group">
<label for="Seller_SellerLegalName">Seller Legal Name</label>
<input class="form-control"
id="Seller_SellerLegalName" required
[(ngModel)]="listingSeller.legalName"
name="legalname"
type="text"
#legalname="ngModel">
</div>
ts文件是
export class SellerComponent implements OnInit {
@Input('listingSeller') listingSeller: Location
@Input('listingForm') listingForm: NgForm
constructor() {}
ngOnInit() {}
}
我正在使用NgForm进行验证, 指令内部没有发生验证,我如何对指令内部的领域进行验证?
答案 0 :(得分:1)
如果您在表单内部使用子表单,请使用Control容器与父表单指令集成。使用viewProviders为现有表单提供ControlContainer
ControlContainer:
ControlContainer是formform指令的超类。
applisting.component.ts
import { Component, OnInit, Input } from '@angular/core';
import { ControlContainer, NgControl, NgForm } from '@angular/forms';
@Component({
selector: 'app-listing',
templateUrl: './listing.component.html',
styleUrls: ['./listing.component.css'],
viewProviders: [ { provide: ControlContainer , useExisting: NgForm} ]
})
export class ListingComponent implements OnInit {
@Input('value') age:number;
constructor() { }
ngOnInit() {
}
}
parent.component.html
<form #f="ngForm" >
Name
<input name="fname" type="text" [(ngModel)]="name">
<app-listing [value]="age"></app-listing>
</form>