-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAngular-Notes.txt
More file actions
2322 lines (1688 loc) · 66.7 KB
/
Copy pathAngular-Notes.txt
File metadata and controls
2322 lines (1688 loc) · 66.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
==========
Angular
=========
-> Angular is a client side framework developed by Google company
-> Angular framework is developed using TypeScript
-> Angular is mainley used for Single Page Applications Development
-> Angular supports multiple devices ( Mobiles & Desktops )
-> Angular supports multiple browsers
-> Angular is free and open source framework
-> Angular JS and Angular both are not same
-> From Angular 2 version onwards it is called as Angular Framework
Note: The current version of Angular is 15
======================
Angular Building Blocks
======================
1) Components
2) Metadata
3) Template
4) Data Binding
5) Module
6) Service
7) Dependency Injection
8) Directives
9) Pipes
-> Angular application is collection of components. In components we will write logic to send data to template and capture data from template. Components are TypeScript classes.
-> Metadata nothing but data about the data. It provides information about components and templates.
-> Template is a view where we will write our presentation logic. In Angular application template is a HTML file. Every Component contains its own Template.
-> Data Binding is the process of binding data between component property and view element in template file.
-> Module is a collection of components, directives and pipes
-> Service means it contains re-usable business logic. Service classes we will inject into Components using Depdency Injection.
-> Dependency Injection is the process of injecting dependent object into target object. In Angular applications services will be injected into components using DI.
-> Directives are used to manipulate DOM elements in the Template.
(We can execute presentation logic based on conditions like if-else , loops etc... using directives)
-> Pipes are used to transform the data before displaying
(lower case to upper case, INR to USD, dd/mm/yyyy to DD-MMM-YYYY)
======================================
Environment Setup For Angular Applications
======================================
1) Install Node JS
2) Install TypeScript
3) Install Angular CLI
4) Install Visual Studio Code IDE
-> Angular 2+ framework is available as a collection of packages, those packages are available in "Node". To use those packages "npm" (Node Package Manager) is must and should..
URL : https://nodejs.org/en/
-> After installing node software, open cmd and type node -v. It should display node version number then installation is successfull.
-> Angular framework itself is developed based on TypeScript. In Angular applications we will write code using TypeScript only.
-> We can install Typescript using Node Package Manager (npm). Open command prompt and execute below command to install TS.
$ npm install -g typescript
-> After TypeScript installation got completed we can verify version number using below command in cmd. If it displays version number then installtion is successfull.
$ tsc -v
-> Install Angular CLI software using below command in TypeScript.
$ npm install @angular/cli -g
-> Check angular installation using below command
$ ng v
-> Download and install VS code IDE
URL : https://code.visualstudio.com/download
Note: We are done with angular setup... lets start building angular applications
============================================================================================
-> Create workspace folder in your file system
-> Open command prompt from your workspace folder then type 'code .' then it will open VS CODE IDE from that folder
-> Open terminal in VS CODE IDE to execute our commands ...
-> To create angular application execute below command in command prompt
$ ng new <app-name>
-> Once application got created, navigate into that application folder and execute below command to run angular application.
$ ng serve
-> Angular applications will be deployed into live server which runs on port number 4200. Once application is deployed we can access that using below URL
URL : http://localhost:4200/
-> We can modify default response in app.component.html file
Goto -> Project folder -> src -> app > app.component.html (edit this file)
==============================================================================================
Angular packages
----------------------------------------------------------------------------------------------
-> @angular/core : This pkg provides classes and interfaces that are related to decorators, components and DI. These are mandatory in every Angular 2+ application.
-> @angular/common : This package provides common directives and pipes which are used in most of the angular applications.
-> @angular/compiler : This package is used to compile "template" into "java script" code. We never invoke angular compiler directley. We will invoke that indirectly using below 2 packages
@angular/platform-browser
@angular/platform-browser-dynamic
-> @angular/platform-browser : This package provides runtime services which are required to run our application in browser.
-> @angular/platform-browser-dynamic : An angular application can have any no.of modules. This package is used to bootstrap (start) a module, which execution should be started automatically when application started.
-> @angular/forms : This package is used to create "two way data bindings" , "validations" in angular 2+ applications. This package works based on another package called "zone.js". This package contains below two modules
a) Forms Module
b) Reactive Forms Module
-> @angular/router : This package is used to create routings (page navigations) in Angular 2+ applications.
-> @angular/http : This package is used to send Ajax request to server and get Ajax response from server.
-> @angular/animations : This package is used to create animations in angular application.
-> @angular/material : This package is used for "angular material design" in angular applications.
-> @angular/cdk : Based on this package only "angular material design" components are developed. So this package must be used while using "@angular/material" package.
-> @angular/cli : This package provides set of commands to create new angular application, components, pipes, directives, services etc.
=============================================================================================
-> In angular application we can have any no.of modules
-> When we run angular application, it starts execution from startup module i.e app-module
-> Angular application boot strapping will begin from app module
-> AppModule will bootstrap AppComponent
-> AppComponent is the default component in Angular application
We can see below files in app module
----------------------------------------------------------------------------------------------
src/app/app.module.ts
src/app/app.component.ts
src/app/app.component.html
src/app/app.component.css
src/app/app.component.spec.ts
src/app/app.module.ts
----------------------
-> This file contains definition of app module
-> Angular app can have any no.of modules. It should at least one module i.e called as "AppModule"
-> This file imports "AppComponent" from app.component.ts file and bootstraps the same in "AppModule"
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
src/app/app.component.ts
-------------------------
-> This file contains defintion of "AppComponent"
-> In Angular application we can have many components. It should contain atleast one component that is called as "AppComponent"
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app1';
}
-> selector is used to invoke the component
-> templateUrl represents presentation logic file (html)
-> styleUrls represents css file(s)
src/app/app.component.html
---------------------------
-> This file contains presentation logic of component
-> Every component will have its own template
-> This template file content will be rendered into
<app-root></app-root> selector tag at index.html
src/app/app.component.css
-------------------------
-> This file contains css syles of "AppComponent"
-> By default this file is empty
src/app/app.component.spec.ts
-----------------------------
-> This file contains test cases for "AppComponent"
-> The test case files should have "spec.ts" file extension
=========================================================================
=> In Angular application "index.html" file will act as wecome file
=> When we access Angular application URL in Browser it will load index.html file
=> In index.html file we are using AppComponent selector to invoke AppComponent.
<app-root></app-root>
---------------------------------------------------------------------------------------------
=> We can create Component in the Angular using below command
$ ng generate component <component-name>
-> When we create new component it will generate 4 files like below
CREATE src/app/greet/greet.component.html (20 bytes)
CREATE src/app/greet/greet.component.spec.ts (619 bytes)
CREATE src/app/greet/greet.component.ts (271 bytes)
CREATE src/app/greet/greet.component.css (0 bytes)
UPDATE src/app/app.module.ts (478 bytes)
-----------------------------------------------------------------------------------------------
Components
-----------------------------------------------------------------------------------------------
-> The component class represents certain section of web page. For example, "login form" is represented as login component.
-> The component class includes "properties" to store the data, "methods" to manipulate the data.
-> Every Angular 2+ application contains at-least one component which is called as "app component". We can create any no.of components in angular application.
-> A component is invoked through a custom tag called as selector. "app component" selector is "<app-root></app-root>".
-> The Component class should have a decorator called "@Component" to define that class as Component class.
Component Class
--------------------------
import {Component} from "@angular/core"
@Component (meta-data)
class ClassName{
property:dataType = value;
method(args) : returnType {
//logic
}
}
Metadata properties of @Component
---------------------------------
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
-> selector : represents tag which is used to invoke the component
-> templateUrl : represents the html file that has to be rendered when the component is invoked
-> template represents content of content
-> styleUrls : Represents the list of styles (css) that have to be loaded for the component.
-> providers : Represents list of services to be imported into the component
-> animations : Represents list of animations to be performed in the component.
-----------------------------------------------------------------------------------------------
Note: The components which we are creating will act as child components for AppComponent.
-> Child Components we will access from AppComponent using Selector.
-----------------------------------------------------------------------------------------------
-> Create Welcome Component & Greet Component
-> Invoke Welcome Component & Greet Component in AppComponent like below
---------------------------app.component.html-------------------------------------------------
<h1> This message from AppComponent</h1>
<app-welcome></app-welcome>
<app-greet></app-greet>
---------------------------------------------------------------------------------------------
Note: Every Component having its own CSS file to apply styles for that component related template logic.
---------------------------------------------------------------------------------------------
Data Bindings
---------------------------------------------------------------------------------------------
-> The "data binding" is used to establish relation between "component" and "template".
-> When the value of "component" is changed, then template will be changed automatically. When the value of "template" is changed, then the "component" will be changed automatically.
-> Data Bindings are four Types
1) Interpolation
2) Property Binding
3) Event Binding
4) Two Way Binding
--------------------
Interpolation
--------------------
-> It is used to display the value of variable / property in template file
-> If the property value is changed then automatically it will be updated in template
syntax : {{propertyName}}
--------------------------
Property Binding
---------------------------
-> Property Binding is used to send the data from component to template and assign the same into an attribute of tag.
-> If the property value is changed then automatically it will be updated in template
Syntax: [attribute]=*property
-----------------------
Event Binding
-----------------------
-> It is used to pass event notifications from template to component
Syntax : <tag (event) = "method()" > </tag>
-----------------------------------
Two-way Data Binding
----------------------------------
-> Two-way data binding is the combination of both property binding and event binding
-> When we change the value of the property then automatically it will be updated in HTML element.
-> When we change the value of HTML element then automatically it will updated in property.
-> "ngModel" is the pre-defined directive which is used to achieve two-way data binding.
-> Two way data binding is applicable only for <input/> and <select/> tags.
-> "FormsModule" must be imported in order to use Two Way Data Binding
-----------------------------------------------------------------------------------------------
Developing Angular application with Two Way Data Binding
---------------------------------------------------------------------------------------------
1) Import FormsModule in app.module.ts file from '@angular/forms' package
2) Declare Variables and function in AppComponent class
3) Write Presentation Logic in app.component.html file (template file)
-----------------------app.module.ts----------------------------------------------------------
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
------------------------app.component.ts-----------------------
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
fname:string = "Adam";
lname:string = "Smith";
age:number=25;
gender:string="Male";
country:string="India";
isEmployed:boolean=true;
handleSubmitBtn(){
this.fname = "John";
this.lname="Buttler";
this.age = 30;
this.gender= "Male";
this.country="USA";
this.isEmployed=false;
}
}
---------------------app.component.html-------------------------
<div>
<h4>Data Bindings Example</h4>
First Name : {{fname}} <br/>
Last Name : {{lname}} <br/>
Age : {{age}} <br/>
Gender : {{gender}} <br/>
Country : {{country}} <br/>
Is Employed : {{isEmployed}} <br/>
<hr/>
First Name : <input type="text" [(ngModel)]="fname"/><br/>
Last Name : <input type="text" [(ngModel)]="lname"/><br/>
Age : <input type="text" [(ngModel)]="age"/><br/>
Gender :
<input type="radio" [(ngModel)]="gender" value="Male">Male
<input type="radio" [(ngModel)]="gender" value="Fe-Male">Fe-Male <br/>
Country :
<select [(ngModel)]="country">
<option>India</option>
<option>USA</option>
<option>UK</option>
</select> <br/>
Is Employed : <input type="checkbox" [(ngModel)]="isEmployed"> <br/>
<input type="button" value="Submit" (click)="handleSubmitBtn()" />
</div>
-----------------------------------------------------------------------------------------------
Angular application with Registration Form
-----------------------------------------------------------------------------------------------
-> Create Angular application
$ ng new registration
-> Import FormsModule from '@angular/forms' package in app.module.ts file
-> Write variables and function in component class to deal with registration form
-> Design presentation logic in Template file (app.component.html)
-> Run angular application
$ ng serve
------------------------app.module.ts--------------------------
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule, FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
-----------------------app.component.ts-------------------------
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
username:string="";
password:string="";
confirmPassword:string="";
gender:string="";
country:string="";
licenseAgreement:boolean=false;
msg:string="";
RegisterClick(){
this.msg = "Username : "+this.username+"<br/>Password:"+this.password
+"<br/>ConfirmPassword:"+this.confirmPassword
+"<br/>Gender : "+this.gender+"<br/>Country : "+this.country
+"<br/>License Agreement : "+this.licenseAgreement;
}
}
--------------------app.component.html------------------------
<h4>Registration</h4>
Username : <input type="text" [(ngModel)]="username"/><br/>
Password : <input type="password" [(ngModel)]="password"/><br/>
Confirm Password : <input type="password" [(ngModel)]="confirmPassword"><br/>
Gender :
<input type="radio" [(ngModel)]="gender" value="Male">Male
<input type="radio" [(ngModel)]="gender" value="Fe-Male">Fe-Male <br/>
Country:
<select [(ngModel)]="country">
<option>-Select-</option>
<option>India</option>
<option>USA</option>
<option>UK</option>
</select> <br/>
<input type="checkbox" [(ngModel)]="licenseAgreement"/> I Accept License Agreement <br/>
<input type="submit" value="Register" (click)="RegisterClick()"/>
<hr/>
<div [innerHTML]="msg"></div>
=============
Directives
=============
-> Directives are used to perform DOM manipulations
----------------------
What is DOM?
----------------------
-> DOM stands for Document Object Model
-> Webpage content will be represented as a tree i.e DOM
-> The HTML DOM is an API (Programming Interface) for JavaScript:
JavaScript can add/change/remove HTML elements
JavaScript can add/change/remove HTML attributes
JavaScript can add/change/remove CSS styles
JavaScript can react to HTML events
JavaScript can add/change/remove HTML events
--------------------------
Built-In Directives
----------------------------
style
--------
-> It is used to set CSS property value dynamically at runtime.
-> When Component property value changed then CSS property value will be changed automatically.
Syntax
------
<tagname [style.cssproperty]="component-property">
----------------------app.component.ts------------------------
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
marks:number=20;
mycolor:string="";
constructor(){
if(this.marks >= 35 ){
this.mycolor="green";
}else{
this.mycolor="red";
}
}
}
-------------------------app.component.html-------------------
<div>
<h3>Style Directive Example</h3>
<div [style.color]="mycolor">{{marks}}</div>
</div>
---------------------------------------------------------------
ngClass
======
-> IT is used to CSS classname dynamically at run time
-> When the value of Component property is changed then css class will be changed automatically.
-> Use this directive to set styles with multiple properties conditionally.
----------------------app.component.css---------------------
.class1{
color:green;
font-size:30px;
}
.class2{
color:red;
font-size:50px;
}
---------------------app.component.html---------------------
<div>
<h3>ngClass Directive Example</h3>
<div [ngClass]="myclass">{{marks}}</div>
</div>
----------------------app.component.ts-----------------------
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
marks:number=80;
myclass:string="";
constructor(){
if(this.marks >=35 ){
this.myclass="class1";
}else{
this.myclass="class2";
}
}
}
-------------------------------------------------------------
ngIf
----
-> The ngIf displays the element if condition is true otherwise it will remove element from DOM.
Syntax:
-------
<tag *ngIf="condition">
</tag>
Note: The ngIf directive must prefix with *
--------------------------app.component.ts---------------------
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
marks:number=80;
b:boolean;
constructor(){
if(this.marks >=35 ){
this.b=true;
}else{
this.b=false;
}
}
}
-----------------app.component.html----------------------------
<div>
<h3>ngIf Directive Example</h3>
<div *ngIf="b" style="background-color:blue;">Congratulations...!!</div>
<div *ngIf="!b" style="background-color: red;">Better luck next time..!!</div>
</div>
-----------------------------------------------------------------------
ngIf and else
-----------------------------------------------------------------------
-> The "ngIf and else" displays one element if it is "true" otherwise it displays other element.
syntax:
-------
<tag *ngIf="condition; then template1;else template2">
</tag>
<ng-template #template1>
...
</ng-template>
<ng-template #template2>
...
</ng-template>
-----------------------app.component.ts------------------------
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
marks:number=80;
b:boolean;
constructor(){
if(this.marks >=35 ){
this.b=true;
}else{
this.b=false;
}
}
}
------------------------app.component.html----------------------
<div>
<h3>ngIf else Directive Example</h3>
<div *ngIf="b;then template1;else template2">
</div>
<ng-template #template1>
<div style="background-color:green;">Congratulations...."</div>
</ng-template>
<ng-template #template2>
<div style="background-color:red">Better luck next time...</div>
</ng-template>
-----------------------------------------------------------------------
-------------
ngSwitch
-------------
-> The "ngSwitch" checks the value of a variable, weather it matches with any one of the cases and displays element when it matches with anyone.
-> Use "ngSwitch" if you want to display some content for every possible value in a variable.
syntax
------
<tag [ngSwitch]="property">
<tag *ngSwitchCase="'value'"></tag>
<tag *ngSwitchCase="'value'"></tag>
<tag *ngSwitchCase="'value'"></tag>
<tag *ngSwitchDefault></tag>
</tag>
---------------------app.component.ts--------------------------------
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
country:string=null;
}
-----------------------app.component.html-------------------------------
<div>
<h4>ngSwitch Example</h4>
<select [(ngModel)]="country">
<option>India</option>
<option>USA</option>
<option>UK</option>
<option>Japan</option>
</select>
<div [ngSwitch]="country">
<p *ngSwitchCase="'India'">India Details Here</p>
<p *ngSwitchCase="'USA'">USA Details Here</p>
<p *ngSwitchCase="'UK'">UK Details Here</p>
<p *ngSwitchCase="'Japan'">Japan Details Here</p>
<p *ngSwitchDefault>Please select country</p>
</div>
</div>
------------------------------------------------------------------------
ngFor
=====
-> It is used to repeat the tag once for each element in the array. It generates (repeats) the given content once for one element of the array.
=> We have to use use prefix '*' before "ngFor"
Usecase: Displaying all products available in shopping cart.
Syntax:
-------
<tag *ngFor="let variable of arrayname">
</tag>
------------------------app.component.ts--------------------------
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
cities:string[] = ["New Delhi", "Mumbai", "Banglore", "Hyderabad"];
}
-----------------------app.component.html----------------------------
<div>
<h4>ngFor Example</h4>
<ul>
<li *ngFor="let city of cities">{{city}}</li>
</ul>
</div>
----------------------------------------------------------------------
ngFor with Object Array
-----------------------
-> Using this technique we can print array of object values in web page.
-> First we have to store set of objects inside array then read objects one-by-one using "ngFor" and display the data in table format.
Usecase: Reading Product details (name & price) and displaying them.
syntax to create object array
------------------------------
arrayRefVariable:classname[] = [
new ClassName(),
new ClassName(),
new ClassName()
];
syntax to use object array using ngFor
---------------------------------------
<tag *ngFor="let variable of arrayRefVariable">
variable.property1
variable.property2
</tag>
ngFor with Object array
-----------------------
-----------------------employee.ts----------------------------
export class Employee{
empId:number;
empname:string;
salary:number;
constructor(a, b, c){
this.empId = a;
this.empname = b;
this.salary = c;
}
}
---------------------app.component.ts--------------------------
import { Component } from '@angular/core';
import { Employee } from './employee';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
employees:Employee[] = [
new Employee(101, "John", 5000),
new Employee(102, "Smith", 5000),
new Employee(103, "Nick", 6000)
];
}
---------------------app.component.html---------------------------
<div>
<h4>ngFor with Object Array Example</h4>
<table border="1">
<tr>
<th>Emp Id</th>
<th>Emp Name</th>
<th>Emp Salary</th>
</tr>
<tr *ngFor="let emp of employees">
<td>{{emp.empId}}</td>
<td>{{emp.empname}}</td>
<td>{{emp.salary}}</td>
</tr>
</table>
</div>
----------------------------------------------------------------
ngFor directive with Add and Remove functionality
-------------------------------------------------
-> We can allow the user to add new records (objects) to existing array. User can also delete existing records.
Adding element to array
-----------------------
arrayVariable.push(value);
Removing element from array
-----------------------------
arrayVariable.splice(index, count);
------------------app.module.ts---------------------------
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
-----------------------employee.ts----------------------------
export class Employee{
empId:number;
empname:string;
salary:number;
constructor(a, b, c){
this.empId = a;
this.empname = b;
this.salary = c;
}
}
----------------------app.component.ts---------------------------
import { Component } from '@angular/core';
import { Employee } from './employee';
@Component({
selector: 'app-root',