@Component({
selector: "app-login",
template: `
`
})
export class LoginComponent {
email = '';
@ViewChild('form') form: FormGroup;
submit(value) {
console.log(value);
}
}
@Component({
selector: "app-login",
template: `
`
})
export class LoginComponent implements OnInit {
loginForm: FormGroup;
ngOnInit() {
this.loginForm = new FormGroup({
email: new FormControl()
});
}
submit() {
console.log(this.loginForm.value);
}
}
Template Driven | Reactive | |
---|---|---|
Form model | HTML template | Defined in a component |
Data model | Unstructured | Structured |
Predictability | Asynchronous | Synchronous |
Form validation | Directives | Functions |
Mutability | Mutable | Immutable |
CVA - is an interface that acts as a bridge between the Angular forms API and a native element in the DOM.It propagates changes from the model to the view and from the view to the model
// is the method that writes a new value from the form model
// into the view or (if needed) DOM property
writeValue(obj: any)
// is a method that registers a handler that should be called
// when something in the view has changed
registerOnChange(fn: any)
// it registers a handler specifically for when a control receives
// a touch event
registerOnTouched(fn: any)
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CustomComponent),
multi: true
}
]
viewProviders: [
{ provide: ControlContainer, useExisting: FormGroupDirective }
]
ViewProviders instead of providers: providers cannot reach up the parent (if the structure is complex)
For Re-validation, the validators will need to be on the top-level form, not at the child component, if you want it to be part of the parent form’s validation.
{
provide: NG_VALIDATORS,
useExisting: forwardRef(() => AddressComponent),
multi: true
}
Object.keys(this.form.controls).forEach(key => {
this.form.get(key).markAsTouched();
});