2020 June 17th
Forms are an important concept to be covered and controlled in the client-side development... in the previous article, I talked about forms in angular and how to manage them easily with Rxjs
.
{% post https://dev.to/muhammedmoussa/hack-angular-forms-with-rxjs-4he7 %}
we will be going with pseudocode for HTML and component coverage and the full code with demo will be included. let's start!
[()]
, with buttons eventually binding into the component class.<div>
<input [(ngModel)]="name" type="text">
<input [(ngModel)]="active" type="checkbox">
<button (click)="onSubmit()">Save</button>
<button (click)="onReset()">Reset</button>
</div>
that's all that we need from our component view. no more logic noise clear or directives.
variables
or props
which will act as form controls, and functions that are will handle form actions like submit
and reset
.export class UserFormComponent {
// controls
name = ''
active = false
onSubmit() {
// collecting component data before submit.
const {name, age} = this
const userData = {name, age}
console.log(userData)
}
onReset() {
// component is clear again.
this.name = '';
this.active = false
}
}
and that's it we have a simple clean component that will act as a solid piece from our greater app!
@Output()
. actually, we almost need the form data when submitting the event but in some cases, we need to emit also reset events to the parent component for any reset stuff related to other components. let's implement both.export class UserFormComponent {
@Output() submit = new EventEmitter<object>()
@Output() reset = new EventEmitter<any>()
onSubmit() {
// collecting component data before submit.
const {name, age} = this
const userData = {name, age}
console.log(userData)
this.submit.emit(userData)
}
onReset() {
this.reset.emit()
}
}
export class UserFormComponent {
onSubmit() {
// validating component data before submit.
if(!this.isValid()) { return }
// ... submit code
}
private isValid(): boolean {
// just required name and active. you can go with your validation logic and add another else if blocks.
const {name, active} = this
if(name && active) {
return true
} else {
return false
}
}
}
#Concolusion 🖐️#
we discussed forms management tips for angular development by using built-in frameworks Data binding and event emitters. in a functional way, BUT this approach not Exclusive at angular think about it functional programming is heavily welcomed in javascript frameworks and the second part is a data binding is a behavior that another framework can offer like VueJs
in v-model
directive. and React
in useState()
hook. so this pattern may be useful at any js framework not only angular.
thought sharing is welcomed since all of that post is just a personal point of view through daily experience.