@AdiSreyaj
Angular has in-built tools to work with forms. Being a framework, this is a really good advantage Angular has over others.
The Angular Forms APIs captures user input events from the view, validate the user input, create a form model and data model to update, and provide a way to track changes.
Both of them work with the same Forms API.
Template Driven Forms
import { Component } from "@angular/core";
@Component({
selector: "app-root",
template:`
<div>
<label for="email">Email</label>
<input type="email" id="email" [(ngModel)]="email" />
</div>
`,
styleUrls: ["./app.component.css"]
})
export class AppComponent {
email = "hi@adi.so";
}
CONTINUED...
Reactive Forms
import { Component } from "@angular/core";
import { FormControl } from "@angular/forms";
@Component({
selector: "app-root",
template: `
<div>
<label for="email">Email</label>
<input type="email" id="email" [formControl]="email" />
</div>
`,
styleUrls: ["./app.component.css"]
})
export class AppComponent {
email = new FormControl("hi@adi.so");
}
HTML form elements like input, radio, checkbox etc has certain properties and events that can be used to interact with them.
// Listent to the user input
input.addEventListener("input", (evt) => {
console.log(evt.target.value);
});
// Update the value of the input field
button.addEventListener("click", () => {
input.setAttribute("value", "Adithya");
});
// Disable the input field
disable.addEventListener("click", () => {
input.setAttribute("disabled", true);
});
Angular has created Control Value Accessors
for all the basic input elements that we have:
Find all Control Value Accessors in the docs
@Directive({
selector:
`input[type=checkbox][formControlName],
input[type=checkbox][formControl],
input[type=checkbox][ngModel]`,
host: {
'(change)': 'onChange($event.target.checked)',
'(blur)': 'onTouched()'
},
providers: [CHECKBOX_VALUE_ACCESSOR]
})
export class CheckboxControlValueAccessor
extends BuiltInControlValueAccessor
implements ControlValueAccessor {
writeValue(value: any): void {
this.setProperty('checked', value);
}
}
Similar to what Angular has done with build-in value accessors, we can create our own accessors by implementing the ControlValueAccessor interface.
interface ControlValueAccessor {
writeValue(obj: any): void
registerOnChange(fn: any): void
registerOnTouched(fn: any): void
setDisabledState(isDisabled: boolean)?: void
}
Let's dive deep into each of these properties!
writeValue(obj: any): void;
registerOnChange(fn: any): void;
registerOnTouched(fn: any): void
setDisabledState(isDisabled: boolean)?: void
Now let's see how its done!
Here are some important links:
Feel free to reach out to me on twitter @AdiSreyaj