Angular Beginner Handbook

Arshad
7 min readJan 21, 2021

--

You need to install three things before starting angular

To install Angular CLI, you need to dial up some commands

npm install -g @angular/cli 

To create a new boilerplate of angular app, dial up

ng new app-name

And start the app using

ng serve

Now your app is running on your machine (most probably on localhost:4200)

Your angular code currently contains the Modules(Component + Services). Minimum one component is necessary, as we have Root Component(called AppComponent) and all other components are nested inside the root component. Module also have Services which contains the business logic of your application.

You can see the App module there and inside that module, you can see the different components. Where you can write your HTML/CSS and TypeScript code.

Inside the app.component.ts

import { Component } from ‘@angular/core’;@Component({  selector: ‘app-root’,  templateUrl: ‘./app.component.html’,  styleUrls: [‘./app.component.css’]})export class AppComponent {  title = ‘hello-world’;}

Here, we have AppComponent Class and we are passing the value title to our HTML file, inside our HTML file

<h1>{{title}}</h1>

The title “Hello World” is seen on your browser now, @Component is telling that the class is component class. And we have meta data in form of

  • selector — this is custom HTML tag which is used to represent AppComponent class. You can see in the index.html file where we are using it like
<app-root></app-root>
  • templateUrl — This is used to link the HTML file, and tells our component about the HTML file and it also contains the address of our HTML file.
  • styleUrls — This is used to style our component and the address of our CSS file.

You can create your new component with the help of the CLI using the command.

ng g c myComponent

Now you can see the new component inside app folder, and all the linking is done automatically by the angular CLI.

You can specify selector by three ways:

  1. First one is the default one that you are seeing [selector: ‘app-test’] and use it like <app-test></app-test>
  2. We can use it like class[selector: ‘.app-test’] and use it like
<div class = “app-test”></div>

3. Third one is like attribute { selector: ‘[app-test]’ } and use it like

<div app-test></div>

You can use your HTML inside the .ts file by changing templateUrl to template and write simple HTML inside that. And same for the CSS.

Interpolation

Interpolation is done in JS by the help of double curly braces

{{ passed_value }} Inside the curly braces you can use any JS logic.

You can’t assign the result of the logic in any variable. You can’t use the global methods inside the curly braces like {{window.location.href}}

Attributes are initialize by HTML and once they are done, they couldn’t change while the Properties are initialize by the DOM and they can be change. Property is the current value, and attribute is the starting value.

Binding

You can bind the property using different methods like interpolation but interpolation have it’s limitations, like if you apply disabled property on input attribute by using interpolation, it doesn’t work. So we use [] for the binding or bind-property_name. See the example for more clear views —

Inside HTML file:

<input [id]=”myId” type=”text” value=”Arshad” /><input bind-disabled=”isDisabled” id=”{{myId}}” type=”text” value=”Arshad” /><input [disabled]=”isDisabled” id=”{{myId}}” type=”text” value=”Arshad” />

Inside TS file:

public myId = ‘testId’;public isDisabled = false;

Class Binding — It can be done by simple ways like

<h2 class=”text-success”>Green heading</h2><h2 [class]=”successClass”>Green heading</h2> 
//successClass contain the class name that is being applied here
<h2 [class.text-success]=”hasError”>Green heading</h2>
//hasError is boolean value
<h2 [ngClass]=”messageClasses”>Green heading</h2>
//messageCla
sses contains the multiple classes

Style Binding

<h2 [style.color]=”hasError ? ‘red’ : ‘green’ ”>Anything</h2>//hasError is the boolean property
  • For multiple property to be bind use ngClass

Event Binding —

<button (click)=”onClick()”>Button</button><button (click)=”onClick($event)”>Button</button>onClick(event){
console.log(event) //all info about the event
}
<button (click)=”greeting='Welcome!'”>Button</button>
{{greeting}} //welcome will be shown when you click on button

Template Reference variables —

You can use all the property of DOM using the reference variable name like

<input #myInput type=”text”>
<button (click)="logMessage(myInput.value)">Log</button>
logMessage(value){
console.log(value)
}

here, all the DOM properties applied in myInput tag.

  • ngIf (if and else conditional statement) —

This is simple if and else statement but the syntax is little different, let’s jump to code for better understanding

<h2 *ngIf=”displayName; else elseBlockId">If executed </h2><ng-template #elseBlockId><h2>Else executed</h2></ng-template>

Here displayName is the boolean variable declared in ts file, either true or false.

Another way of using this conditional statement is

<div *ngIf=”displayName; then thenBlockId; else elseBlockId"><div><ng-template #thenBlockId><h2>True</h2></ng-template><ng-template #elseBlockId><h2>False</h2></ng-template>

This is executed as, if displayName is true then thenBlockId will be executed otherwise elseBlockId is executed.

  • ngSwitch (switch statement) —

This is simple switch statement, like in other languages. Let’s jump to the code for better understanding

<div [ngSwitch] = “color”>
<div *ngSwitchCase=”red”></div>
<div *ngSwitchCase=”yellow”></div>
<div *ngSwitchCase=”green”></div>
<div *ngSwitchCaseDefault></div> //for no match of color
</div>
public color = "red"; //in ts file
  • ngFor ( for loop) —
<div *ngFor = “let color of colors; index as i”>
<h2>{{i}} {{color}}</h2>
</div>
<div *ngFor = “let color of colors; first as f”>
<h2>{{f}} {{color}}</h2> //only first f is true, all other false
</div>
<div *ngFor = “let color of colors; last as l”>
<h2>{{l}} {{color}}</h2> //only last l is true, all other false
</div>

We can also do this for odd and even.

  • Component Interaction

a. Send data from parent component to child component, vice versa.

Let’s first see how to send the data from parent to child component —

Step 1. Define the property in parent.component.ts file. Let’s suppose define public name = “ramu” in the ts file.

Step 2. Pass it through parent.component.html file. Like <app-child [parentData] = “name”></app-child> Here we access the data in child component by using name parentData.

Step 3. Now it’s time to use this variable in our child component.

- In our ts file, also import Input class
@Input public parentData
- In our parent.component.html file
<h2>{{parentData}}</h2>

In case if we want to change the name of the variable that we are using here, then we can do this like @Input(“parentData”) public anotherName. Now, we can use this parent data by using the variable name anotherName.

b. Passing data from child to parent component.

This is not easy here, we can’t simply pass the data in the, because we don’t have parent component selector here in the child component. So, we take the help of the event, to pass the data.

Step 1. Create a new instance of eventEmitter in child.component.ts like @Output() public childEvent = new EventEmitter();

Step 2. Create a button to fire that event like <button (click)=”fireEvent()”></button> in the child.component.html file.

Step 3. Now when the button is clicked then fireEvent() function will execute, so we need to create that event in the child.component.ts file like

fireEvent(){

this.childEvent.emit(“Passing this string”)

}

the whole code look alike —

<button (click)=”fireEvent()”></button> //in the cdhild.component.html//in the child.component.ts file 
@Output() public childEvent = new EventEmitter();
fireEvent(){
this.childEvent.emit(“Passing this string”)
}

Step 4. In the parent.component.html file we listen the event

<app-child (childEvent)=”message=$event”></app-child>

Don’t forgot to create the variable inside the parent.component.ts file public message = “”;

  • Pipes

Pipes are used to change the view data in the angular. Let’s see the code for better understanding.

Let’s define the name variable in the ts file public name = “Ramu” and after this heads to our HTML file of that component.

Pipes in strings —

<h2>{{ name }}</h2>    //Ramu<h2>{{ name | lowercase }}</h2>    //ramu<h2>{{ name | uppercase }}</h2>    //RAMU<h2>{{ name | titlecase }}</h2>    //Ramu<h2>{{ name | slice:1:2}}</h2>    //am<h2>{{ jsonData | json }}</h2>    //the representation is in JSON

Now, see how to use pipes in numbers —

<h2>{{ 5.678 | number:'1.2-3'}}</h2>    //5.678<h2>{{ 5.678 | number:'3.4-5'}}</h2>    //005.6780<h2>{{ 5.678 | number:'3.1-2'}}</h2>    //005.67<h2>{{ 0.25 | percent }}</h2>           //0.25%

Here number:1.2–3 means minimum 1 digit left to the number, and minimum 2 digit in the number and maximum 3.

Pipes in Data —

First create a date variable in the ts file like —

public date = new Date();

And after this, let’s heads to HTML file —

<h2> {{ date }} </h2><h2> {{ date | date:'short' }} </h2><h2> {{ date | date:'shortDate' }} </h2><h2> {{ date | date:'shortTime' }} </h2>
  • Services — Let’s suppose, you want to show some data on two or more web pages, then you have to do all the data accessing process, again and again. So, to reduce the repetition, we use the services. To create a service, we simple use the command ng g s serviceName and the service will be created automatically. You can do all your work here and return the data. Now, you created your service and now you need to register it with injector. Always register your service on module level(App module), so each component can use the service by importing the service. So, go to the app.module.ts and there you find the providers array, write the name of your service in that array [serviceName], also don’t forget to import the service. Now use this service in the component in which you need, so to use this shorthand code of typescript inside the ts file of the component constructor. Also when the component initializes the ngOnInit() hook will be initializes. We also declare it in that hook.
constructor(private _employeeService: EmployeeService){}public employees = [];ngOnInit(){
this.employee = this._employeeService.getEmployees();
}

Now, we can use employee array which is imported from the services in our HTML component.

I found this playlist helpful in learning angular - https://bit.ly/35ZFrwu

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Arshad
Arshad

No responses yet

Write a response