Skip to content

Instantly share code, notes, and snippets.

@bastijns-jeroen
Last active April 10, 2017 19:00
Show Gist options
  • Select an option

  • Save bastijns-jeroen/24fbe0584186b1433be523332a79c21c to your computer and use it in GitHub Desktop.

Select an option

Save bastijns-jeroen/24fbe0584186b1433be523332a79c21c to your computer and use it in GitHub Desktop.
A reusable address form component
@Component({
selector: 'address-form-component',
template: `
<form [formGroup]="form">
<div class="form-group">
<label for="street">street</label>
<input name="street" class="form-control" type="text" formControlName="street" />
<div *ngIf="form.get('street').touched">
<div *ngIf="form.get('street').hasError('required')">This field is required.</div>
</div>
</div>
<div class="form-group">
<label for="housenumber">housenumber</label>
<input name="housenumber" class="form-control" type="text" formControlName="housenumber" />
<div *ngIf="form.get('housenumber').touched">
<div *ngIf="form.get('housenumber').hasError('required')">This field is required.</div>
</div>
</div>
<div class="form-group">
<label for="city">city</label>
<input name="city" class="form-control" type="text" formControlName="city" />
<div *ngIf="form.get('city').touched">
<div *ngIf="form.get('city').hasError('required')">This field is required.</div>
</div>
</div>
<div class="form-group">
<label for="zipcode">zipcode</label>
<input name="zipcode" class="form-control" type="text" formControlName="zipcode" />
<div *ngIf="form.get('zipcode').touched">
<div *ngIf="form.get('zipcode').hasError('required')">This field is required.</div>
</div>
</div>
<button id="save" type="submit" [disabled]="!form.valid">save</button>
</form>
`
})
export class AddressFormComponent implements OnInit {
@Output()
private formReady : EventEmitter<FormGroup> = new EventEmitter<FormGroup>();
private form: FormGroup;
constructor(private fb: FormBuilder) {
this.form = this.fb.group({
"street": new FormControl("", Validators.required),
"housenumber": new FormControl("", [Validators.required, Validators.pattern(/\d+/g)]),
"city": new FormControl("", Validators.required)
"zipcode": new FormControl("", [Validators.required, Validators.pattern(/\d+/g)])
});
}
ngOnInit(): void {
this.formReady.emit(this.form);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment