Last active
October 28, 2022 16:31
-
-
Save Audhil/e70f6d88fcfb6e6d1c806f7a09efd273 to your computer and use it in GitHub Desktop.
Angular Basics
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
DOM(https://youtu.be/ipkjfvl40s0) - Document Object Model | |
object as a tree structure | |
DOM is an object-oriented representation of web page | |
Component(https://youtu.be/16rQyEQtpyQ?list=PLC3y8-rFHvwhBRAgFinJR8KHIrCdTkZcZ): | |
Template(view/HTML) + Class(code/typescript/data&methods) + Metadata(information decorator) | |
3 ways of declaring selector | |
1 -> selector: 'app-badwords' -> <app-badwords></app-badwords> in html file | |
2 -> selector: '.app-badwords' -> <div class="app-badwords"></div> in html file | |
3 -> selector: '[app-badwords]' -> <div app-badwords></div> | |
2 ways of declaring templates | |
1 -> templateUrl: './badwords.component.html' | |
2 -> template:`<div> | |
Inline template | |
</div>` | |
2 ways of declaring styles | |
1 -> styleUrls: ['./badwords.component.scss'] | |
2 -> styles: [` | |
div{ | |
color: red; | |
} | |
`] | |
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// | |
DATABINDING: | |
Interpolation(https://youtu.be/2a6OfacW_-I?list=PLC3y8-rFHvwhBRAgFinJR8KHIrCdTkZcZ): | |
template:`<div> | |
Welcome {{name}}! | |
</div>` | |
template:`<div> | |
Welcome {{name+ "jack and jill"}}! | |
</div>` | |
template:`<div> | |
Welcome {{name.toUpperCase()}}! | |
</div>` | |
template:`<div> | |
Welcome {{greetUser()}}! | |
</div>` | |
template:`<div> | |
Welcome {{siteUrl}}! | |
</div>` | |
export class TComponent{ | |
siteUrl = window.location.href; | |
} | |
Property Binding(https://youtu.be/N8FBmB2jme8?list=PLC3y8-rFHvwhBRAgFinJR8KHIrCdTkZcZ): | |
HTML Attribute vs DOM property | |
$0.getAttribute('value') - it'll hold initial value, will not respond to value changes | |
$0.value -> DOM property - it'll get changed dynamically, when value changes | |
property binding: | |
template:`<div> | |
<input [id]="myId" type="text" value="mohammed"> | |
<input id="{{myId}}" type="text" value="mohammed"> // this is valid, works only for string values | |
<input [disabled]="false/true" type="text" value="mohammed"> | |
<input [disabled]="isDisabled" type="text" value="mohammed"> | |
<input bind-disabled="isDisabled" type="text" value="mohammed"> // another way of doing property binding | |
</div>` | |
export class TComponent{ | |
public myId = "testId"; | |
public isDisabled = true/false; | |
} | |
Class Binding(https://youtu.be/Y6OP-lPJxgs?list=PLC3y8-rFHvwhBRAgFinJR8KHIrCdTkZcZ): | |
template:`<div> | |
<h2 class="text-success">Jack and jill</h2> | |
<h2 [class]="succcessClass">Jack and jill</h2> | |
<h2 class="text-special" [class]="succcessClass">Jack and jill</h2> // it'll take succcessClass property, ignoring attribute "class=" value - either use one way of class binding | |
<h2 [class.text-danger]="hasError">Jack and jill</h2> // conditionally applying class to the attribute | |
<h2 [ngClass]="messageClasses">Jack and jill</h2> // adds multiple class binding | |
</div>`, | |
styles:[ | |
` | |
.text-success{ | |
color: green; | |
} | |
.text-danger{ | |
color: red; | |
} | |
.text-special{ | |
font-style: italic; | |
} | |
` | |
] | |
export class TComponent{ | |
public succcessClass = "text-success"; | |
public hasError = false; | |
public isSpecial = true; | |
public messageClasses = { | |
"text-success": !this.hasError, | |
"text-danger": this.hasError, | |
"text-special": this.isSpecial | |
} | |
} | |
Style Binding(https://youtu.be/q256X6-u9Q8?list=PLC3y8-rFHvwhBRAgFinJR8KHIrCdTkZcZ): | |
template:`<div> | |
<h2 [style.color]="'orange'">Jack and jill</h2> // changing color property of CSS | |
<h2 [style.color]="hasError ? 'red' : 'green'">Jack and jill</h2> // changing color property of CSS | |
<h2 [style.color]="highLightColor">Jack and jill</h2> // changing color property of CSS | |
<h2 [ngStyle]="titleStyles">Jack and jill went up the hill</h2> | |
</div>`, | |
styles:[] | |
export class TComponent{ | |
public hasError = false; | |
public highLightColor = "orange"; | |
public titleStyles = { | |
color: "blue", | |
fontStyle: "italic" | |
} | |
} | |
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// | |
EVENTBINDING: | |
template:`<div> | |
<button (click)="onClick()">Click!</button> | |
{{greeting}} | |
<button (click)="onClick2($event)">Click!</button> // passing event data | |
<button (click)="greeting='Jack and jill went up the hill! '">Click!</button> | |
</div>`, | |
styles:[] | |
export class TComponent{ | |
public greeting = ""; | |
onClick(){ | |
console.log('Jack and jill went up the hill'); | |
this.greeting = "Hi hello?!"; | |
} | |
onClick2(event){ | |
console.log(event); | |
} | |
} | |
Template reference variables(https://youtu.be/Oo0-r_YhoJs?list=PLC3y8-rFHvwhBRAgFinJR8KHIrCdTkZcZ): | |
template:`<div> | |
<input #myInput type="text"> | |
<button (click)="logMessage(myInput.value)">Click!</button> | |
</div>`, | |
styles:[] | |
export class TComponent{ | |
logMessage(value){ | |
console.log(value); | |
} | |
} | |
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// | |
Two-Way binding: | |
for eg., Form validation: | |
import {FormsModule} from '@angular/forms;' | |
@NgModule( | |
imports=[ | |
BrowserModule, | |
FormsModule | |
] | |
) | |
export class AppModule{ | |
} | |
template:`<div> | |
<input [(ngModel)]="name" type="text"> | |
{{name}} | |
</div>`, | |
styles:[] | |
export class TComponent{ | |
public name=""; | |
} | |
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// | |
*ngIf="truthy/falsy" | |
template:`<div> | |
<h2 *ngIf="true">jack and jill went up the hill</h2> | |
<h2 *ngIf="false">2nd line</h2> // remove the element from the DOM tree itself -> check with inspect element | |
// with property | |
<h2 *ngIf="displayName">3rd line</h2> | |
// if - else | |
<h2 *ngIf="displayName; else elseBlock">4th line</h2> | |
<ng-template #elseBlock> | |
<h2> | |
Name is Hidden! 5th line | |
</h2> | |
</ng-template> | |
// separate ngIf with if block & else block | |
<div *ngIf="displayName; then thenBlock; else elseBlock"></div> | |
<ng-template #thenBlock> | |
<h2>this is If block</h2> | |
</ng-template> | |
<ng-template #elseBlock> | |
<h2>this is Else block</h2> | |
</ng-template> | |
</div>`, | |
styles:[] | |
export class TComponent{ | |
public displayName=true; | |
} | |
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// | |
ngSwitch | |
template:`<div [ngSwitch]="color"> | |
<div *ngSwitchCase="'red'">You picked red color</div> | |
<div *ngSwitchCase="'blue'">You picked blue color</div> | |
<div *ngSwitchDefault>You didn't pick any color, pick again</div> | |
</div>`, | |
styles:[] | |
export class TComponent{ | |
public color="red"; | |
} | |
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// | |
ngFor | |
template:` | |
<div *ngFor="let color of colors"> | |
<h2>{{color}}</h2> | |
</div> | |
<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> | |
</div> | |
<div *ngFor="let color of colors; last as l"> | |
<h2>{{l}} {{color}}</h2> | |
</div> | |
<div *ngFor="let color of colors; odd as o"> | |
<h2>{{o}} {{color}}</h2> | |
</div> | |
<div *ngFor="let color of colors; even as e"> | |
<h2>{{e}} {{color}}</h2> | |
</div> | |
`, | |
styles:[] | |
export class TComponent{ | |
public colors=["red", "blue", "orange"]; | |
} | |
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Input & @Output decorators(https://youtu.be/BGy8DdGw_WE?list=PLC3y8-rFHvwhBRAgFinJR8KHIrCdTkZcZ): | |
Parent to Child communication: | |
// parent component | |
template: ` | |
<app-badwords [parentName]="name"></app-badwords> | |
` | |
export class AppComponent { | |
public name = "Mohammed Audhil"; | |
} | |
// child component | |
template: ` | |
<h2>{{"Hello man! "+parentName}}</h2> | |
<h2>{{"using alias: "+nameIs}}</h2> | |
` | |
export class BadwordsComponent implements OnInit { | |
@Input() public parentName = ""; // bind data with interpolation | |
@Input('parentName') public nameIs = ""; // bind data with interpolation | |
} | |
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// | |
Child to Parent communication: | |
Child: | |
@Component({ | |
selector: 'app-badwords', | |
template:` | |
<p>Click the button to send event to parent Component</p> | |
<button (click)="onClick()">Click!</button>`, | |
styleUrls: ['./badwords.component.scss'] | |
}) | |
export class BadwordsComponent implements OnInit { | |
@Output() public childEvent = new EventEmitter(); | |
onClick() { | |
this.childEvent.emit('Jack and jill went up the hill!'); | |
} | |
constructor() { } | |
ngOnInit(): void { | |
} | |
} | |
Parent: | |
@Component({ | |
selector: 'app-root', | |
template:` | |
<app-badwords (childEvent)="message=$event" [parentName]="name"></app-badwords> | |
{{"value from child component: "+message}} | |
`, | |
styleUrls: ['./app.component.scss'] | |
}) | |
export class AppComponent { | |
public message: string = ""; | |
} | |
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Pipes: transforms the data only for view, DOES NOT change value of the property | |
string, number, currency, date pipes | |
@Component({ | |
selector: 'app-root', | |
template:` | |
<!-- sting pipes --> | |
<h2>{{name | lowercase}}</h2> <!-- mohammed audhil --> | |
<h2>{{name | uppercase}}</h2> <!-- MOHAMMED AUDHIL --> | |
<h2>{{msg | titlecase}}</h2> <!-- Jack And Jill Went Up The Hill --> | |
<h2>{{msg | slice:3}}</h2> <!-- k and jill went up the hill --> | |
<h2>{{msg | slice:3:10}}</h2> <!-- k and j --> | |
<h2>{{person | json}}</h2> <!-- { "name": "mohammed Audhil", "age": 33, "sex": "male" } --> | |
<!-- number pipes --> | |
<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.68 --> | |
<h2>{{.25 | percent}}</h2> <!-- 005.68 --> | |
<!-- currency pipes --> | |
<h2>{{.25 | currency}}</h2> <!-- $0.25 --> | |
<h2>{{.25 | currency: 'INR'}}</h2> <!-- ₹0.25 --> | |
<h2>{{.25 | currency: 'INR': 'code'}}</h2> <!-- INR0.25 --> | |
<!-- date pipes --> | |
<h2>{{dateIs}}</h2> <!-- Thu Oct 27 2022 22:05:30 GMT+0530 (India Standard Time) --> | |
<h2>{{dateIs | date: 'short'}}</h2> <!-- 10/27/22, 10:06 PM --> | |
<h2>{{dateIs | date: 'shortDate'}}</h2> <!-- 10/27/22 --> | |
<h2>{{dateIs | date: 'shortTime'}}</h2> <!-- 10:06 PM --> | |
`, | |
styleUrls: ['./app.component.scss'] | |
}) | |
export class AppComponent { | |
public name = "Mohammed Audhil"; | |
public msg = "jack and jill went up the hill"; | |
public person = { | |
name: "mohammed Audhil", | |
age: 33, | |
sex: "male" | |
}; | |
public dateIs = new Date(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Purpose of Service | |
1. share data - between components | |
2. implement application logics - calculations, data transformations | |
3. external interaction - db, network calls | |
@Injectable represents, this service class may have some injected dependencies(in future), | |
to inject a service to another service we should have this decorator | |
employee.service.ts | |
import { Injectable } from '@angular/core'; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class EmployeeService { | |
constructor() { } | |
getEmployees(){ | |
return [ | |
{"id": 1, "name": "mohammed audhil", "age": 13}, | |
{"id": 2, "name": "Arun", "age": 23}, | |
{"id": 3, "name": "Karthik", "age": 33}, | |
{"id": 4, "name": "sundar", "age": 13}, | |
]; | |
} | |
} | |
//////////////////////////////////////////////////////////////////////////////////////////////////////// | |
app.module.ts | |
@NgModule({ | |
declarations: [ | |
AppComponent, | |
BadwordsComponent, | |
EmployeeComponent, | |
EmployeeListComponent | |
], | |
imports: [ | |
BrowserModule | |
], | |
providers: [EmployeeService], | |
bootstrap: [AppComponent] | |
}) | |
export class AppModule { } | |
//////////////////////////////////////////////////////////////////////////////////////////////////////// | |
@Component({ | |
selector: 'app-employee-list', | |
template:` | |
<h2>Employee List</h2> | |
<ul *ngFor="let emp of employees"> | |
<li>{{emp.id}} : {{emp.name}} : {{emp.age}}</li> | |
</ul> | |
`, | |
styleUrls: ['./employee-list.component.scss'] | |
}) | |
export class EmployeeListComponent implements OnInit { | |
public employees : any[]= []; | |
constructor(private _employeService: EmployeeService) { } | |
ngOnInit(): void { | |
this.employees = this._employeService.getEmployees(); | |
} | |
} | |
//////////////////////////////////////////////////////////////////////////////////////////////////////// | |
@Component({ | |
selector: 'app-employee', | |
template:` | |
<h2>Employee Component</h2> | |
<ul *ngFor="let emp of employees"> | |
<li>{{emp.id}} : {{emp.name}} : {{emp.age}}</li> | |
</ul> | |
`, | |
styleUrls: ['./employee.component.scss'] | |
}) | |
export class EmployeeComponent implements OnInit { | |
public employees : any[]= []; | |
constructor(private _employeService: EmployeeService) { } | |
ngOnInit(): void { | |
this.employees = this._employeService.getEmployees(); | |
} | |
} | |
//////////////////////////////////////////////////////////////////////////////////////////////////////// |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
app.modules.ts | |
import { NgModule } from '@angular/core'; | |
import { BrowserModule } from '@angular/platform-browser'; | |
import {HttpClientModule} from '@angular/common/http'; | |
import { AppComponent } from './app.component'; | |
import { EmployeeComponent } from './employee/employee.component'; | |
import { EmployeeListComponent } from './employee-list/employee-list.component'; | |
import { EmployeeService } from './employee.service'; | |
@NgModule({ | |
declarations: [ | |
AppComponent, | |
EmployeeComponent, | |
EmployeeListComponent | |
], | |
imports: [ | |
BrowserModule, | |
HttpClientModule, | |
], | |
providers: [EmployeeService], | |
bootstrap: [AppComponent] | |
}) | |
export class AppModule { } | |
//////////////////////////////////////////////////////////////////////////////////////////////////////////////// | |
employee.service.ts | |
import { HttpClient, HttpErrorResponse } from '@angular/common/http'; | |
import { Injectable } from '@angular/core'; | |
import { IEmployee } from './employee'; | |
import { catchError } from 'rxjs/operators'; | |
import { Observable, throwError } from 'rxjs'; | |
@Injectable({ | |
providedIn: 'root' | |
}) | |
export class EmployeeService { | |
private url = "/assets/data/employees.json"; | |
constructor(private http: HttpClient) { } | |
// replace url with real API url | |
getEmployeesFromServer() : Observable<IEmployee[]> { | |
return this.http.get<IEmployee[]>(this.url) | |
.pipe(catchError(this.errorHandling)); | |
} | |
errorHandling(error: HttpErrorResponse) { | |
return throwError(error.message || 'server Error'); | |
} | |
getEmployees(){ | |
return [ | |
{"id": 1, "name": "mohammed audhil", "age": 13}, | |
{"id": 2, "name": "Arun", "age": 23}, | |
{"id": 3, "name": "Karthik", "age": 33}, | |
{"id": 4, "name": "sundar", "age": 13}, | |
]; | |
} | |
} | |
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// | |
employee-list.component.ts | |
import { Component, OnInit } from '@angular/core'; | |
import { EmployeeService } from '../employee.service'; | |
@Component({ | |
selector: 'app-employee-list', | |
template:` | |
<h2>Employee List</h2> | |
<ul *ngFor="let emp of employees"> | |
<li>{{emp.id}} : {{emp.name}} : {{emp.age}}</li> | |
</ul> | |
<h2>{{errorMsg}}</h2> | |
`, | |
styleUrls: ['./employee-list.component.scss'] | |
}) | |
export class EmployeeListComponent implements OnInit { | |
public employees : any[]= []; | |
public errorMsg = ""; | |
constructor(private _employeService: EmployeeService) { } | |
ngOnInit(): void { | |
// this.employees = this._employeService.getEmployees(); | |
this._employeService.getEmployeesFromServer() | |
.subscribe(data => this.employees = data, | |
error => this.errorMsg = error | |
); | |
} | |
} | |
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// | |
employee.component.ts | |
import { Component, OnInit } from '@angular/core'; | |
import { EmployeeService } from '../employee.service'; | |
@Component({ | |
selector: 'app-employee', | |
template:` | |
<h2>Employee Component</h2> | |
<ul *ngFor="let emp of employees"> | |
<li>{{emp.id}} : {{emp.name}} : {{emp.age}}</li> | |
</ul> | |
<h2>{{errorMsg}}</h2> | |
`, | |
styleUrls: ['./employee.component.scss'] | |
}) | |
export class EmployeeComponent implements OnInit { | |
public employees : any[]= []; | |
public errorMsg = ""; | |
constructor(private _employeService: EmployeeService) { } | |
ngOnInit(): void { | |
// this.employees = this._employeService.getEmployees(); | |
this._employeService.getEmployeesFromServer().subscribe(data => this.employees = data, | |
error => this.errorMsg = error); | |
} | |
} | |
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// | |
employee.ts | |
export interface IEmployee { | |
id: number, | |
name: string, | |
age: number | |
} | |
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////// |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment