Intro to Angular 6 using Game of Flags
Starting Angular 6 can be a daunting task specially if you are unaware of component style web architectures and new to ES6/typescript world. Rather than jumping to Heroes Tour on official Angular Site we can make some interesting application to learn the basics of Angular components and service objects.
TLDR ;
In this article we will create a small game — Game of Flags (not Thrones :P ). All code is hosted on GitHub here and all steps are shown in a screencast hosted on this Youtube link. If you are a pro — Go there.
Ingredients Required :
- Code Editor (I prefer VSCode)
- Node and NPM installation
- Angular 6 CLI installed on your system [ check if `ng` command works]
Steps :
- Create a new project using
ng new
command. This will create the Angular 6 scaffold for a new app. I have chose namegof
ng new gof
2. Move to newly create folder gof
using cd
command
cd gof
At this point you can check using ng serve
command that your angular application is working perfectly on http://localhost:4200
3. Create a new component using ng generate component
command
ng generate component flag
This will generate a flag
component which is by default called via app-flag
tag in your root component
. We will come back to this point in later part of article.
4. Open flag.component.html
in flag component folder. Here you can create a basic text input box and button using simple HTML code. We will use this button to generate random flags and input for guessing name of nation.
5. You will need a list of all countries to generate random countries data — as we will later use a CSS library called flag-icon-css
which depends on ISO Codes of countries — like IN for India. I will download the use all.json
data given on Github repo https://github.com/lukes/ISO-3166-Countries-with-Regional-Codes/blob/master/all/all.json
6. To store all this data — it is a good idea to create a Service in Angular. We will used ng generate service
command to generate a data service.
ng generate service countries
This will create file countries.service.ts
in root folder. Here we can paste our countries data in one function called getCountries
Here how it will look like :
export class CountriesService {constructor() { }getCountries(){return [{“name”:”Afghanistan”,”alpha-2":”AF”,.....] //all data}
7. Now we can import CountriesService
inside our flag.component.ts
Use import statements like this
import { CountriesService } from '../countries.service';
Also we will need to add the Service variable to our constructor to use it properly. I called it cService
constructor(private cService: CountriesService) { }
8. Now let’s implement a function called next()
which will be called on click of our button in Flag component. We will implement logic to generate random
number to a range of countries
array indexes. So we can pick a random country and its name, ISO code properties.
Here is what it will look like
next(){let countries = this.cService.getCountries();let random = Math.floor(Math.random()*countries.length);this.randomNationName = countries[random].name;this.randomNationISOCode = countries[random]['alpha-2']console.log(this.randomNationISOCode,this.randomNationName)}
Don’t forget to declare randomNationName
and randomNationISOCode
at top of class.
9. Finally to check the function we need to attach this to our button using click
event binding
<button (click)="next()">Fire</button>
Now you can check in your browser that you are getting random names and ISO code of countries.
10. We have not yet implemented flag logic. We will use github project called flag-icon-css
to perform this. You can install this library via npm using
npm install flag-icon-css
This will install it in node_modules
. We can use this CSS in our component using @Component
decorators
@Component({selector: 'app-flag',templateUrl: './flag.component.html',styleUrls: ['./flag.component.css',
'../../../node_modules/flag-icon-css/css/flag-icon.css']})
Finally you can check whether CSS is working or not by attaching the style on your flag.component.html
<span class="flag-icon flag-icon-gr"></span>
Here gr
represents ISO code of Greece in lowercase. Check if this works for you — or you have made some mistake in attaching CSS files. However, the flag size will be small by default. You can change it by changing the inline-style to this.
<span style="width:10em; line-height: 10em" class="flag-icon flag-icon-gr"></span>
11. Let add some logic so that we can get random flag on clicking of Fire
button. Logic is simple just replace flag-icon-gr
with flag-icon-{{randomNationISOCode}}
. However ISO codes are by default in uppercase we can use Angular Pipes to make them in lower case.
<span style="width:10em; line-height: 10em" class="flag-icon flag-icon-{{randomNationISOCode | lowercase}}"></span>
Now you can check that you are getting a random flag on click of Fire button. You can also show the randomNationName
with flags — just to verify.
11. Final part of game requires us to
- remove the nation name from HTML
- create a variable
myGuess
and attach it to input box usingngModel
directive - And finally add a conditional alert shown using
*ngIf
to check whethermyGuess
is equal torandomNationName
or not.
All this can be done via this code snippet ( flag.component.html
)
<div><div><span style="width:10em;line-height: 10em" class="flag-icon flag-icon-{{randomNationISOCode | lowercase}}"></span></div><input type="text" [(ngModel)]="myGuess" placeholder="enter name of nation"><button (click)="next()">Fire</button><h1 *ngIf="myGuess && myGuess==randomNationName">Correct Guess !!!</h1></div>
Please note that you will need to import FormsModule
in app.module.ts
for using ngModel
directive.
import { FormsModule } from '@angular/forms';/// at top of fileimports: [BrowserModule,FormsModule //add this part],
12. Tada !! you game is ready and you can play it via click on Fire
button and putting on your guesses.
There are lot of improvement you can do in this game — making UI changes, making guess via multiple choices rather than typing and making friendly alerts etc.
Here is one screenshot of my Output :