Data Transmission
Forms
Controls
It can be used in Service
Routers
Data Transmission
EventEmitter can be used in data transmission between child and parent.
Angular has EventEmitter class and Output decorator that is used in data transmission between child and parent.
EventEmitter class extends RxJS Subject. Subject extends Observable. So EventEmitter is a kind of Observable.
When a value is passed to emit(), the emit() method passes the emitted value to the next() method of any subscribed observer.
When a value is emitted through the output decorator's property, then in the parent component subscribe to the event.
For Example, we need to add a close functionality, decorate the close property with @Output Decorator of type EventEmitter.
EventEmitter Component
//close property
@Output() close = new EventEmitter<any>()
//Inside a function emit the value
this.close.emit("Close Window");
Template
<someselector (close)="onClose($event)"></someselector>
Here we are using () around the emitted event name close. close is a custom event. Then access the event object with the $event argument.
Controls
It can be used in Form Control value changes.
AbstractControl class has a valueChanges property that emits an event every time when the value of the FormControl changes. Examples are Dropdown value changes, Checkbox value changes, Radio button value changes. Controls are part of the form.
Form Value Changes
Whenever FormControl, FormArray, or FormGroup changes Angular form will emit an event that can be get through valueChanges property. valueChanges property returns Observable. Here Observables are used to respond to user input events.
Control Component
//form control property
acceptLicense: new FormControl(false)
//subscribe to acceptLicense property value change
this.acceptLicense.valueChanges.subscribe(checked => {
if (checked) {
this.reactiveFormGroup.addControl('acceptLicense', new FormControl());
} else {
this.reactiveFormGroup.removeControl('acceptLicense');
}
});
Control's HTML Template
<input type="checkbox" formControlName="acceptLicense">
HTTP
HTTP get method returns an Observable
HttpClient returns Observables from HTTP method call like GET, PUT, POST. etc. Observables emits response as a result.
Example
getEmployeeName(empName: string): Observable {
return this.http.get(this.apiURL + 'employees/' + userName)
}