Forms in Angular

Posted on

in

,

Most of the code is in the HTML. Here are the main points:

On the ‘form’ element itself add ‘novalidate’ attribute to turn off the default validation that some browsers have, have a name, as well as ‘ng-submit=”formName.$valid && Ctrl.submitFunction()”. The last bit does the submit function (not the submit button), checks if the form with the name is valid and if so does the function in the controller js.

‘ng-model’ attribute tells angular which property in the Controller this input field represents. It binds the form element’s result to a value that lets another area on the page auto update when the form’s inputs are changed.

Adding ‘required’ to any form elements make it so you have fill in the field properly for the form to be valid.

To make radio buttons required use ng-required=”!Ctrl.curFormEntry.property”. curFromEntry would be declared as a variable in the Controller like so this.curFromEntry = {}; and represents all the data in the current form.

Angular also has build in classes that tell whether a field has been touched and whether it’s currently active or not. You can use css to show this info to the user like so:

.ng-invalid.ng-dirty{
 border-color: red;
}

.ng-valid.ng-dirty{
 border-color:green;
}

View the demo

Download the demo

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

About me

Mark Wong is a front end developer with 10+ years experience. Most of his knowledge of HTML5, CSS and Js is self taught.

Calendar

December 2024
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
3031