Learning Angular 8 - Lab 2 (Basic Concepts)

Introduction

 
To learn more, please go through my previous labs on Angular 8.
 
 

Angular Project structure and important files

 
This will be quite basic if I explain every file. I will run through some important files and their users.
 
Let’s start with the project structure and files. This is a new test project created using Angular CLI. Basically, the file to run the application has been created. App component files are in the app folder of the project.
 
 
 
These are some important files that you guys need to take a close look at. I will explain them later in the course.
  1. package.json
  2. angular.json
  3. tslint.json
  4. app.component.ts
  5. app.module.ts
  6. main.ts
  7. index.html

Angular behind the scenes

 
If you see the project structure, the Angular framework will add the app.component.html file along with other files by default. However, this file is not the one which the server is served as a response HTML. Index.html is the page actually being served. Angular actually allows us to create a single page application. Here index.html is the single page.
 
Index.html
  1. <!doctype html>  
  2. <html lang="en">  
  3. <head>  
  4.   <meta charset="utf-8">  
  5.   <title>MyTestApp</title>  
  6.   <base href="/">  
  7.   <meta name="viewport" content="width=device-width, initial-scale=1">  
  8.   <link rel="icon" type="image/x-icon" href="favicon.ico">  
  9. </head>  
  10. <body>  
  11.   <app-root></app-root>  
  12. </body>  
  13. </html>
If you see in index.html there is only one setting <app-root></app-root> in the body but the result is showing text from app.component.html.
 
 
 
As we know now, using the Angular framework we can create a single page application.
 
Come to the main.js file and see how it wires up the application to start.
 
 
 
  1. platformBrowserDynamic().bootstrapModule(AppModule)  
  2.   .catch(err => console.error(err));
Here you can see AppModule is being bootstrapped and this will start the Angular application which later bootstraps other available components.
 
app.module.ts
 
  1. bootstrap: [AppComponent]
Basically, bootstrap array has an app.component registered which actually tells angular to insert code from there.
 
 
 
app.component.ts has a selector which was injected an index HTML and uses app HTML code to render the HTML back as response.
  1. import { Component } from '@angular/core';  
  2.   
  3. @Component({  
  4.   selector: 'app-root',  
  5.   templateUrl: './app.component.html',  
  6.   styleUrls: ['./app.component.css']  
  7. })  
  8. export class AppComponent {  
  9.   title = 'my-test-app';  

We will go quite deep for components later in the course but right now it’s important to understand how the sector is injected from main.ts to index.html, which is a single page rendered and will actually run the HTML code from app.componen.html.
 

Data Binding in Angular

 
Data binding is a very important concept for angular application. It can be defined as a way to ensure a communication from Business logic (data) and UI (html dom). In angular apps, we have typescript code which contains logic and UI user experience.
 
 

One-way Binding

 
Typescript code to HTML
 
1. String Interpolation
 
String Interpolation is a one-way databinding communication from TypeScript code to HTML template (view). It uses the template expression in double curly braces to display the data from the component to the view.
 
{{any data/expression}}
  1. <div class="row">  
  2. <div class="col-xs-12">  
  3. <button class="btn btn-primary" (click)="onAddCourse()">Add New Course</button>  
  4. </div>  
  5. </div>  
  6. <p>{{ statusMessage }}</p>  
  7. <p>{{ result * 10 }}</p> 
2. Property Binding
 
Property Binding is also a one-way data-binding technique in which a property of an HTML element to a field which is a defined property in the component TypeScript code. This is also one-way communication from typescript code to HTML.
 
[property] = ” any data”
 
Here you can see I am trying to work with the disabled attribute of a button and set the property which resolves to a boolean result.
 
The square bracket indicates to Angular that property binding is being used, we want to dynamically add some property and disable the HTML attribute. The HTML element in DOM has multiple properties with it.
  1. <div class="row">     
  2.     <div class="col-xs-12">  
  3.         <button class="btn btn-primary" (click)="onAddCourse()"  
  4.             [disabled]="!isDisabled"  
  5.             >Add New Course</button>  
  6.     </div>  
  7. </div> 
Typescript code
  1. isDisabled= false;
Result
 
 
 
I have created an example with hardcoded values for Disabled =false which is bound to a disabled property of the dom element. You can write any code to understand it.
 
b) HTML to Type script Code
 
Event Binding
 
Event binding provides a way to communicate from HTML down to the component. It handles the events raised from the HTML DOM. The methods code bind with this event will reach once this event happens. Similar to how in a button click event a method is called in the component which has some logic written and it will react to that event in dom.
 
HTML code: below you can see there is click event listener with a button bound with a method onAddCourse() which is setting a message in typescript code. That message is commutated back to HTML with a message which users string interpolation to produce the result.
 
You can write any logic which will run on a button click.
  1. <div class="row">     
  2.     <div class="col-xs-12">  
  3.         <button class="btn btn-primary" (click)="onAddCourse()">Add New Course</button>  
  4.     </div>  
  5.   
  6. </div>  
  7. <p>{{ statusMessage }}</p> 
Component code
  1. import { Component, OnInit } from '@angular/core';  
  2. @Component({  
  3.   selector: 'app-course-list',  
  4.   templateUrl: './course-list.component.html',  
  5.   styleUrls: ['./course-list.component.css']  
  6. })  
  7. export class CourseListComponent implements OnInit {  
  8.   statusMessage:string =null;  
  9.   constructor() { }  
  10.   ngOnInit() {  
  11.   }  
  12.   onAddCourse()  
  13.   {  
  14.        this.statusMessage="New Course added !!!";  
  15.   }  
  16. }
Passing data in event binding
 
When using event binding data, it can also be passed from the template using $event variable.
 
Taking an example where I want to output a course name from the input element on every keystroke, as well as the out the name in the template.
 
I have used an (input) event which actually runs on every keystroke.
  1. <div class="row">     
  2.     <div class="col-xs-12">  
  3.   
  4.         <input type="text"   
  5.                class="form-control"   
  6.                (input)=onupdateCourse($event)   
  7.         >  
  8.         <br>  
  9.         <button class="btn btn-primary" (click)="onAddCourse()"  
  10.             [disabled]="!isDisabled"  
  11.             >Add New Course</button>  
  12.     </div>  
  13. </div>  
  14. <br>  
  15. {{ courseName }}
Let’s print the event data and analyze the target property which has value “Test”
 
 
 
  1. onupdateCourse(event :Event)  
  2. {  
  3.     console.log(event);  
  4.     this.courseName= (<HTMLInputElement>event.target).value;  
  5. }
Using the above code, the courseName variable can be set to the value of the HTML input element value from the event target.
 

Two-way Binding - Communication in both directions

 
 
Two-way binding is another way to update HTML template and the TypeScript code. Basically, model and view will be in real time sync and any changes will reflect both ways.
  1. <input type="text" class="form-control" [(ngModel)]="courseName" > 
[(ngModel)]="courseName" , ngModel directive is needed to do two way binding.
import { FormsModule } from '@angular/forms';
 
It depends upon FormsModule in angular/forms package, so we have to add a FormsModule in imports[] array in the AppModule.
 

Conclusion

 
Keep learning and keep smiling.
 
Resources and Useful Links
 
Thanks to the authors of the below links:
 


Similar Articles