#
Angular Callback function (example)
This tutorial explains to you what a callback function is and how to use a callback function. In this article you will have an example as well.
For this example I have used the code generated at the article named Create a Child Component in Angular.
I have modified the following files:
app.component.html
<!--This is app.component.html file -->
<div style="text-align:center">
<div class="myclass">
</div>
<app-child1></app-child1>
</div>
app.component.ts
/* This is app.component.ts file */
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
message: string = 'Enjoy setTimeout !';
}
app.component.css
/* This is app.component.css file */
.myclass {
background-color: rgb(52, 144, 224);
}
child1.component.ts
/* This is child1.component.ts file */
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-child1',
templateUrl: './child1.component.html',
styleUrls: ['./child1.component.css']
})
export class Child1Component implements OnInit {
constructor() { }
ngOnInit() {
this.functionNr1(() => {console.log("DO something in callBackFunction();")} );
}
functionNr1(callBackFunction) {
this.functionNr2();
console.log("Hello 1 from functionNr1 ["+new Date()+"]");
callBackFunction();
console.log("Hello 2 from functionNr1 ["+new Date()+"]");
}
functionNr2() {
var num:number = 0
var count1:number = 0;
var count:number = 0;
console.log("START: functionNr2 ["+new Date()+"]");
for(num=0;num<=2000000000;num++) {
if (num % 2 == 0) {
count1 = count1 + 2;
}
if (num % 3 == 0) {
count1 = count1 + 2;
}
if (num % 4 == 0) {
count1 = count1 - 2;
}
count++;
}
console.log("END: functionNr2 ["+new Date()+"]");
}
}
child1.component.html
<!--This is child1.component.html file -->
<div>
child1 works!
</div>
When you run the application, you will see:
But the more important thing, you will see in the console:
You can see, the callback function
is called when another function is completed.
This is a nice feature in an asynchronous environment like Angular
(this is the main usage of a callback in Angular).
Info
As you can see the callback function is passed as a function parameter in Angular.