Last active
October 29, 2016 09:43
-
-
Save dherges/525d206bed2e58ded035e0daf07affa9 to your computer and use it in GitHub Desktop.
Angular2: reactive v. template-driven form
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component, OnInit } from '@angular/core' | |
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms' | |
@Component({ | |
selector: 'reactive-form', | |
template: | |
` | |
<form [formGroup]="myForm" (ngSubmit)="submit()"> | |
<div class="form-group"> | |
<label for="name">Name</label> | |
<input type="text" class="form-control" id="name" | |
formControlName="name"> | |
</div> | |
<div class="form-group"> | |
<label for="quantity">Quantity</label> | |
<input type="number" class="form-control" id="quantity" | |
formControlName="quantity"> | |
</div> | |
<div class="form-group"> | |
<input type="submit" class="form-control" value="Submit" | |
[disabled]="myForm?.invalid"> | |
</div> | |
</form> | |
<h6>FormGroup Model (<code>myForm.value</code>)</h6> | |
<div><pre><code>{{ myForm?.value | json }}</code></pre></div> | |
` | |
}) | |
export class ReactiveFormComponent implements OnInit { | |
myForm: FormGroup; | |
constructor( | |
private fb: FormBuilder | |
) {} | |
ngOnInit() { | |
// build the form model | |
this.myForm = this.fb.group({ | |
name: new FormControl('', Validators.required), | |
quantity: this.fb.control(123) | |
}) | |
} | |
submit() { | |
console.log("Reactive Form submitted: ", this.myForm); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment