Define a filed should has validation:
Export class Demoformsku { myform:controlgroup; Sku:abstractcontrol; Constructor (Fb:formbuilder) { this. MyForm = Fb.group ({ "SKU": ["" ", Validators.required] }); This this. myform.controls[' SKU ']; } OnSubmit (value) { console.log (value); }}
Form message
<*ng-if= "!myform.valid" class= "bg-warning"> Form is invalid</div>
Field message
<*ng-if= "!sku.valid" class= "bg-warning"> SKU is invalid</div>
Field Coloring
<Divclass= "Form-group"[Class.has-error]= "!sku.valid && sku.touched"> <label for= "Skuinput">Sku</label> <inputtype= "text"class= "Form-control"ID= "Skuinput"placeholder= "SKU"[Ng-form-control]= "myform.controls[' sku ')"> </Div>
Specific validation
<*ng-if= "myform.haserror (' Required ', ' SKU ')"> SKU is Required </div>
Import {Component, View, Form_directives, validators, Formbuilder, ngif} from ' Angular2/angular2 '; @Component ({sel Ector: ' Demo-form-sku '}) @View ({directives: [Form_directives, Ngif], Template: '<Div> <H2>Demo Form:sku</H2> <!--Ngform is attched to the form, and #f = "form" form was also come from Ngform - <form[Ng-form-model]= "MyForm"(Submit)= "OnSubmit (myform.value)"> <Divclass= "Form-group"[Class.has-error]= "!sku.valid && sku.touched"> <label for= "Skuinput">Sku</label> <inputtype= "text"class= "Form-control"ID= "Skuinput"placeholder= "SKU"[Ng-form-control]= "myform.controls[' sku ')"> </Div> <Div*ng-if= "!sku.valid"class= "Bg-warning">SKU is invalid</Div> <Buttontype= "Submit"class= "Btn Btn-default">Submit</Button> <Div*ng-if= "myform.haserror (' Required ', ' SKU ')">SKU is required</Div> </form> <Div*ng-if= "!myform.valid"class= "Bg-warning">Form is invalid</Div> </Div> `}) Export class Demoformsku {myform:controlgroup; Sku:abstractcontrol; Constructor (fb:formbuilder) {this.myform = Fb.group ({"SKU": ["" ", Validators.required]}); This.sku = this.myform.controls[' sku '); } onSubmit (value) {Console.log (value); }}
[Angular 2] Validation