首页 > 代码库 > [Angular2 Form] Create and Submit an Angular 2 Form using ngForm

[Angular2 Form] Create and Submit an Angular 2 Form using ngForm

Forms in Angular 2 are essentially wrappers around inputs that group the input values together into an object and also check that all the inputs are valid. Angular 2 ‘sngForm allows you to get a reference to that object and validity and use them to display information about the form or use the ngSubmit event to save information from the form.

 

Make sure you need to add ‘name‘ prop to both form and input fields. This helps to structure the form model.

  <form action="" name="myForm" #formRef="ngForm" (ngSubmit)="onSubmit(formRef.value)">    Firstname: <input type="text" name="firstName"ngModel required>    <button [disabled]="!formRef.valid">Submit</button>  </form>  <pre>    form value: {{formRef.value | json}}    form valid: {{formRef.valid | json}}  </pre>

 

ngModel is reuqire by ngForm, so you need to use ngModel on input field even you don‘t assign anything to it.

[Angular2 Form] Create and Submit an Angular 2 Form using ngForm