forked from sanjaysamantra1/angular_notes
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathangular Notes.txt
More file actions
2874 lines (2064 loc) · 96.6 KB
/
angular Notes.txt
File metadata and controls
2874 lines (2064 loc) · 96.6 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 installation
====================
1. download Nodejs and install
https://nodejs.org/en/download/
2. check nodejs is installed
node -v (in command prompt)
3. check if NPM is installed (NPM-Node Package Manager)
npm -v
4. install angular CLI (Command Line Interface)
npm install -g @angular/cli
OR
npm install -g @angular/cli@latest
OR
npm install -g @angular/cli@17
5. check if angular CLI is installed??
ng v
npx ng v
ng help
6. create a new angular project (go to the folder where project needs to be created)
ng new project1 (project1 - name of the project, can be any other valid name)
ng new your-angular-project --defaults
you will be prompted for few things, just select 'yes' (enter)
1. CSS/SCSS/LESS - select css
7. Run the project / Start the project
in command prompt go to the project directory (ex: c:/users/sanjay/angular/project1)
Run the Below command
ng serve
(OR)
ng serve --open
(OR)
ng s -o (step-8 is not required)
-ng serve command launches the server, watches your files, and rebuilds the app as you make changes to those files.
8. open your browser and open the below URL
http://localhost:4200
-To Run the project in other port
ng serve --port 5000 --open
npx @angular/cli new angular-internationalization-example --style=css --routing=false --skip-tests
vscode extensions
=================
1. ESLint
2. prettier
3. code spell checker
4. gitlens
5. vscode-icons
6. thunderclient
Chrome Extensions
=================
1. Mobile Simulator
2. Angular DevTools
3. Redux DevTools
4. JsOn Viewer
Angular
=======
-Angular is a platform and framework for building single-page client applications using HTML and TypeScript.
-A framework is a set of helper functions,tools and rules that help us to build our application.
-Angular is a collection of well-integrated libraries that cover a wide variety of features including routing,forms management, client-server communication, and more
-Angular is a suite of developer tools to help us develop, build, test, and update our code. (Angular CLI)
Framework Library
=========================================================================
-group of libraries to make our work easier -performs specific operations
-provides ready to use tools,standards -provides reusable functions for our code
templates for fast application development
-Collection of libraries & APIs -collection of helper functions,objects
-cann't be easily replaceable -can be easily replaceable
-angular,vue -jQuery,lodash,momentjs,ReactJs
-Hospital with full of doctors -A doctor specialized in 1 thing
React Angular
===========================================================
1. Library-2013 1. Framework-2009
2. Light-weight 2. Heavy
3. JSX + Javascript 3. HTML + Typescript
4. Uni-Directional 4. two-way
5. Virtual DOM 5. Regular DOM
6. Axios 6. HttpClientModule
7. No 7. Dependency Injection
8. No 8. Form Validation
9. extra libraries needed 9. No additional libraries
10. UI heavy 10. Functionality heavy
Bootstrapping angular Application
=================================
-Bootstrapping is a technique of initializing/loading our Angular application.
1. index.html --> <app-root></app-root> (component)
2. main.ts --> bootstrapApplication(AppComponent, appConfig)
3. app.config.ts --> configuration information about our application (Application level route info)
4. app.component.ts-->app.component.html-->app.component.css
steps to bootstrap the application:
1. Load index.html
2. Load Angular, Other Libraries, and Application Code
3. Execute main.ts File
4. Load Application-Level Module
5. Load Application-Level Component
6. Process Template
Modules
=======
-Module in Angular refers to a place where we can group the components, directives, pipes, and services, which are related to the application.
-Modules are used in Angular to put logical boundaries in your application. instead of coding everything into one application, we can instead build everything into separate modules to separate the functionality of your application.
-In case we are developing a website, the header, footer, left, center and the right section become part of a module.
-Every application should have at least one Angular module, the root/app module, which must be present for bootstrapping the application on launch.
important properties of module are:
----------------------------------
-declarations: The set of components, directives, and pipes that belong to this module
-exports: set of components, directives, and pipes declared in this NgModule that should be visible and usable in the component templates of other NgModules.
-imports: Other modules whose exported classes are needed by component templates declared in this NgModule.
-providers: The set of injectable objects that are available in the injector of this module.
-bootstrap: The main application view, called the root component, which hosts all other app views. Only the root NgModule should set the bootstrap property.
-entryComponents: set of components to compile when this NgModule is defined, so that they can be dynamically loaded into the view
-schemas: Elements and properties that are neither Angular components nor directives must be declared in a schema
-id: A name or path that uniquely identifies this NgModule in getModuleFactory
-jit: When present, this module is ignored by the AOT compiler
Component
=========
-Components are the most basic UI building block of an Angular app.
-An Angular app contains a tree of Angular components.
-Each component defines a class that contains application data and logic, and is associated with an HTML template that defines a view to be displayed.
-@Component() decorator identifies the class immediately below it as a component, and provides the template and related component-specific metadata.
https://angular.io/api/core/Component#description
@Component configuration options:
--------------------------------
selector: Ex: 'app-header'
template: `<div>This is header Component</div>`
templateUrl: './header.component.html'
style: ['.class1{color:red}']
styleUrl: ['./header.component.css']
encapsulation: ViewEncapsulation.ShadowDom
providers: [Services]
changeDetection:ChangeDetectionStrategy.OnPush
viewProviders: []
animations: []
interpolation: []
entryComponents: []
preserveWhitespaces?: boolean
standalone?: boolean
imports:[]
schemas?:[]
Decorators
==========
@NgModule - Decorator that marks a class as an NgModule
@Component - Decorator marks a class as an Angular component
@Directive - Decorator marks a class as an Angular Directive
@Injectable - Decorator marks a class as an Angular Service
@Pipe - Decorator marks a class as an Angular Pipe
@Input - collect data from parent component
@Output - Child component emits event to parent component
@HostBinding - Binds value to the host element (custom directive)
@HostListener - listens event from the host element (custom directive)
@ViewChild -
@ViewChildren -
@ContentChild -
@ContentChildren -
Angular CLI
===========
-Angular CLI is a command-line interface tool used to initialize, develop, scaffold, and maintain Angular applications directly from a command shell
ng g c demo --dry-run --flat --skip-tests --inline-template --inline-style
g: Generate
c: Component
--flat : No Sub folder for the component(header/footer)
--skip-tests : No test specification file
--inline-template : No Linked Template
--inline-style : No external CSS file
--dry-run : Will display the update without execution
scaffold usage
--------- --------
project ng new <ProjectName>
Component ng g component my-new-component
Directive ng g directive my-new-directive
Pipe ng g pipe my-new-pipe
Service ng g service my-new-service
Class ng g class my-new-class
Guard ng g guard my-new-guard
Interface ng g interface my-new-interface
Enum ng g enum my-new-enum
interceptor ng g interceptor my-interceptor
Resolver ng g resolver my-resolver
Module ng g module my-new-module
https://angular.io/cli/generate
Angular Project - Folder Structure
==================================
.editorconfig : Configuration for code editors. See EditorConfig.
.gitignore : Specifies intentionally untracked files that Git should ignore.
README.md : Introductory documentation for the application.
angular.json : CLI configuration defaults for all projects in the workspace, including configuration options for build, serve, and test tools that the CLI uses, such as TSLint, Karma, and Protractor. For details, see Angular Workspace Configuration.
package.json : Configures npm package dependencies that are available to all projects in the workspace. See npm documentation for the specific format and contents of this file.
package-lock.json : Provides version information for all packages installed into node_modules by the npm client. See npm documentation for details. If you use the yarn client, this file will be yarn.lock instead.
src/ : Source files for the root-level application project.
node_modules/ : Provides npm packages to the entire workspace. Workspace-wide node_modules dependencies are visible to all projects.
tsconfig.json : The base TypeScript configuration for projects in the workspace. All other configuration files inherit from this base file. For more information, see the Configuration inheritance with extends section of the TypeScript documentation.
tslint.json : Default TSLint configuration for projects in the workspace.
How to Use Bootstrap in Angular
===============================
-Bootstrap can be used in Angular either by using CDN or by installing.
1. npm install bootstrap
2. add the below line in 'styles.css'
@import 'bootstrap/dist/css/bootstrap.css'
3. add 'node_modules/bootstrap/dist/js/bootstrap.bundle.min.js' in 'angular.json'
projects->architect->build->scripts array
How to Display Images from local folder
=======================================
1. place the images inside 'public' folder
2. use it in HTML file
<img src='sachin.jpg' />
Databinding
===========
-automatic synchronization of data between Component(TS) and view(HTML).
1. interpolation {{ }} (1-way) (component-->view)
2. property Binding [ ] (1-way) (component-->view)
bind-property (bind-innerHTML)
3. Event Binding ( ) (1-way) (view-->component)
(click) / on-click
4. 2-way Binding [(ngModel)] (2-way) (component<-->view)
bindon-ngModel
Note:For 2-way bindning "FormsModule" should be imported
InterPolation: for concatenating strings;Doesn't work with boolean values
Property: to set an element property to a non-string data value.
2-way Binding:
1. import FormsModule
a. import { FormsModule } from '@angular/forms'
b. imports: [ FormsModule]
2. in view file use [(ngModel)]='variable'
<input type="text" [(ngModel)]='x'>
<input type="text" on-keyup="userIdChanged()" [(ngModel)]="userId" />
(OR)
<input [(ngModel)]="userId" (ngModelChange)="onUserIdChange($event)" />
onUserIdChange(userId: number): void {
console.log('Value Changed');
}
Attribute Binding
=================
-Attribute Binding is needed while working with HTML attributes that do not have corresponding DOM properties, such as colspan, aria-* , data-* attributes
-attributes are defined by HTML and properties are defined by the DOM.
-The attributes main role is to initializes the DOM properties. once the DOM initialization complete, the
attributes job is done.
-Property values can change, whereas the attribute values don't change.
-Property Reflects real-time state changes, whereas Attribute Doesn't change dynamically after creation.
var value1 = document.getElementById('inputBox1').getAttribute('value');
var value2 = document.getElementById('inputBox1').value;
console.log(value1, value2); // type something in the box & run these again
<button [attr.aria-label]="ariaLabel">Click me</button>
there is no equivalent DOM property for aria-label
<table [width]='myWidth' [attr.height]='myHeight'></table>
<tr><td [attr.colspan]="1 + 1">One-Two</td></tr> Correct
<tr><td [colSpan]="1 + 1">One-Two</td></tr> Correct
<tr><td [colspan]="1 + 1">One-Two</td></tr> Wrong
Note: 'colspan' is attribute whereAs 'colSpan' is property.
Variables in templates
======================
-Angular has two types of variable declarations in templates:
1. local template variables
2. template reference variables.
Local template variables with @let
==================================
@let syntax allows to define a local variable and re-use it across a template.
@let cannot be reassigned after declaration
Angular automatically keeps the variable's value up-to-date with the given expression
@let declarations cannot be accessed by parent views or siblings
@let name = user.name;
@let greeting = 'Hello, ' + name;
@let data = data$ | async;
@let pi = 3.1459;
@let coordinates = {x: 50, y: 100};
Template Reference variables
============================
-allows to reference DOM elements present in the template
-access and manipulate DOM elements, child components, or directives
-access in the template without directly accessing them in the TypeScript code.
-They are only accessible within the same template.
-In the template, we use the hash symbol, # or 'ref' to declare a template variable.
<input #phone placeholder="phone number" />
OR
<input ref-phone placeholder="phone number" />
Assignments:
1. Have a paragraph & a toggle button, on click of the button control the visibility(Show/Hide) of the paragraph
2. Create a text-area with maxLength=100, as the user keeps typing display updated Remaining characters.
3. Create dropdown with state names, when user changes dropdown value, print the selected dropdown value in a paragraph
4. have 2 inputBoxes, and a dropdown(+,-,*,/) and perform arithmetic operations
5. create a input box, toggle the type of that input box to (text/password)
6. create a counter example with 3 controls(increment,decrement,reset)
7. Have a toggle button and control Dark/Light theme of a page.
CSS
****
1. inline
2. internal
3. styles[] in component
styles: ['h1 { color:red; }']
4. styleUrl / styleUrls in component
5. styles.css global
Note:- the styles written in component's css file applies only to one component.
They are not inherited by any components nested within the template nor by any content projected into the component
View Encapsulation
******************
View encapsulation defines whether the template and styles defined within the component can affect the whole application or vice versa.
Angular provides below encapsulation strategies:
1. Emulated (default) - styles from main HTML(index.html) propagates to the component.
Styles defined in component are scoped to that component only.
2. None - styles from the component propagate back to the main HTML and therefore are visible to all components on the page.
Be careful with apps that have None components in the application.
3. shadowDOM - Use shadowDOM for style encapsulation (only component css will be applied)
1. CSS won't come from main HTML to Component.
2. css will be provided from parent to child component.
ex:- encapsulation: ViewEncapsulation.Emulated(default)
encapsulation: ViewEncapsulation.ShadowDom
encapsulation: ViewEncapsulation.None
Emulated: index HTML--->parent Component (yes)
index HTML-->child component (yes)
Parent(Emulated) --> child(Emulated) (No)
ShadowDom: index HTML--->parent Component(shadowDOM) (No)
index HTML-->child component (No)
Parent (shadowDOM) --> child(Emulated) (Yes)
Parent (shadowDOM) --> child(ShadowDom) (No)
None: index<--->parent Component(None)<-->child component
Directives
**********
-Directives Enhance the power of HTML elements.
-Directives add additional behavior to elements in Angular applications.
-Before Angular 17 (*ngIf , *ngSwitchCase, *ngFor)
-After angular-17 (@if , @else , @switch , @case , @default , @for, @let)
1. Structural Directives :
Directive which changes the layout/structure of the DOM.
* is used with structural directives.
only 1 structural directive can be applied to an element.
2. Attribute Directives : ([ngStyle],[ngClass])
Directive which changes behaviour/appearance of the DOM element.
[ ] is used with attribute direcives.
many attribute directives can be applied to an element.
Note : Compononent can also be considered as directive, because it powers up the html by creating Custom Element, but the directives cannot be considered as component because it does not have a View (template and templateUrl cannot be used in directives)
@if(!flag){
<h1>truuuuuuuuuuuuu</h1>
}@else{
<h1>Falseeeeeeeeeeeeeeeeeeeee</h1>
}
@if() vs hidden
===============
-when @if() condition is false, the element will neither be displayed on the page/screen nor it will be there in the DOM.
-when [hidden] condition is true, the element will not be displayed on the page/screen(display:none) but it will be there in the DOM.
Switch Case
===========
@switch (n) {
@case (1) { <h1>Monday</h1> }
@case (2) { <h1>Tuesday</h1> }
@case (3) { <h1>Wednesday</h1> }
@case (4) { <h1>Thursday</h1> }
@case (5) { <h1>Friday</h1> }
@case (6) { <h1>Saturday</h1> }
@case (7) { <h1>Sunday</h1> }
@default { <h1>Not a Valid number</h1>> }
}
@for()
======
1. for with array , @for with @empty
@for(car of cars;track car;let i = $index){
<h4>{{car}}----{{i}}</h4>
} @empty {
Empty list of cars
}
2. @for() with String
@for(char of str;track char){
<div>{{char}}</div>
}
3. @for with Iterable objects (Map)
@for (entry of myMap; track entry){
<div>{{entry[0]}} === {{entry[1]}}</div>
}
4. @for() with index
@for (item of items; track item; let index = $index) {
<li>{{ index }}: {{ item }}</li>
}
-Before Angular 17 (index,first,last,even,odd)
-After Angular 17 ($index,$first,$last,$even,$odd,$count)
ngFor trackBy
-------------
-trackBy is required. It is used to optimize performance by preventing unnecessary change detection runs when the data changes.
-ngFor by default tracks list items using object identity. This means that if you build a list of new objects from scratch with the exact same values as the previous list and pass this newly built list to ngFor, Angular will not be able to tell that a given list item is already present or not.
-NgForOf needs to uniquely identify items in the iterable to correctly perform DOM updates when items in the iterable are reordered, new items are added, or existing items are removed.
-In all of these scenarios it is usually desirable to only update the DOM elements associated with the items affected by the change. This behavior is important to:
Migrate/convert from old syntax to new syntax
=============================================
ng generate @angular/core:control-flow
Assignment:
==========
-Declare an array of users, display users in card & table format.
add a button/switch to toggle between table view and card view.
https://jsonplaceholder.typicode.com/users
ngStyle
=======
-ngStyle is used to apply some style conditionally.
<p [style.color]="num % 2 == 0 ? 'blue' : 'red'"> Add a style </p>
<p [style.fontSize.px]='48'> Add style with unit </p>
<p [style.background-color]=" flag?'green':'blue' "> Add style conditionally </p>
<p [ngStyle]="condition ? myStyle1 : myStyle2"> NgStyle for multiple values </p>
<p [ngStyle]="myFunction()"> NgStyle for multiple values </p>
ngClass
=======
-ngClass is used to apply css classes conditionally
-Add/Remove Single Class :
<div [ngClass]="{'active': isActive}">
<div [class.active]="isActive">
-Multiple Conditional Classes :
<div [ngClass]="{'active': isActive, 'disabled': isDisabled}">
-Array of Classes:
<div [ngClass]="['class1', 'class2', isActive ? 'active' : 'inactive']">
-Combining Object and Array :
<div [ngClass]="['common-class', { 'active': isActive, 'disabled': isDisabled }]">
<p [class.myClass]='flag'> Add a class to an element </p>
<p [ngClass]="myClasses"> Add Multiple classes to an element </p>
<p [ngClass]="myFunction()"> Add Multiple classes to an element </p>
<button class="btn" [ngClass]="flag ? 'btn-success' : 'btn-danger'">
Class Binding example
</button>
ng-template , ng-container
==========================
-<ng-template> directive represents an Angular template.
-content of this <ng-template> will contain part of a template, that can be composed together with other templates in order to form the final component template.
-Angular is already using <ng-template> under the hood in many of the structural directives that we use all the time: ngIf, ngFor and ngSwitch
-Angular <ng-container> is a grouping element that doesn't interfere with styles or layout because Angular doesn't put it in the DOM.
-if we need a helper element for nested structural directives.<ng-container> can be used instead of creating an un-nscessary element(<div>).
ng-content/ Content projection
==============================
-used to create configurable components.
-Components that are used in published libraries make use of <ng-content> to make themselves configurable.
-if We want to insert HTML elements or other components in a component, then We do that using the concept of content projection.
-We achieve content projection using <ng-content></ng-content>
https://www.freecodecamp.org/news/everything-you-need-to-know-about-ng-template-ng-content-ng-container-and-ngtemplateoutlet-4b7b51223691/
child
======
<ng-content></ng-content>
<ng-content select="#div1"></ng-content>
<ng-content select=".div2"></ng-content>
<ng-content select="span"></ng-content>
parent
======
<h1 id="div1">Registration Form</h1>
Read data from a JSON file
==========================
1. create a JSON file (employees.json/products.json/users.json)
[ {},{},{} ]
2. in tsconfig.json add the below option under 'compilerOptions'
"resolveJsonModule": true,
3. import the data & use in component file (products.component.ts)
import * as data from './products.json';
myProducts = (data as any).default; // inside the class
4. use 'myProducts' in HTML file
<div *ngFor="let prod of myProducts"> </div>
How to use font-awesome (https://fontawesome.com/v4/icons/)
=======================
1. ng add @fortawesome/angular-fontawesome
(OR)
npm install @fortawesome/angular-fontawesome @fortawesome/fontawesome-svg-core @fortawesome/free-solid-svg-icons
2. import { FontAwesomeModule } from '@fortawesome/angular-fontawesome';
import { faStar } from '@fortawesome/free-solid-svg-icons';
imports: [FontAwesomeModule]
3. <fa-icon [icon]="faStar"></fa-icon>
ngxPagination
=============
1. install ngxpagination module
npm install ngx-pagination
2. add ngxpaginationModule to our component
import {NgxPaginationModule} from 'ngx-pagination';
imports: [ NgxPaginationModule,CommonModule]
3. use the below code in html
@for(user of users | paginate: { itemsPerPage: 4, currentPage: p};track $index){
}
<pagination-controls (pageChange)="p = $event"></pagination-controls>
Assignment:
-Read data from a static array and display list of products
https://fakestoreapi.com/products
-implement pagination
-implement search functionality (Search By Title)
-implement sort functionality (Price Asc, Price desc)
How to use SweetAlert (https://sweetalert2.github.io/)
=====================
1. npm i sweetalert2
2. import sweet-Alert in your component
import Swal from 'sweetalert2'
3. on button click call a function, which has the below code
Swal.fire('Good job!', 'You clicked the button!', 'success');
How to use snackbar
===================
1. npm i awesome-snackbar
2. import Snackbar from 'awesome-snackbar'
3. new Snackbar('Helloooo, Good Morning', { position: 'top-center', theme: 'light', timeout: 2000 });
https://snackbar.awesome-components.com/
https://www.npmjs.com/package/ngx-toastr
Assignment
----------
1. create 1 EmployeeCRUD component
2. display list of employees in a table(data comes from an array)
3. user should be able to delete Employee (ask user confirmation)
4. view the details of each employee in a modal (bootstrap Modal)
5. add a new employee to the table (insert a new record to the array)
use sweetAlert to display messages ('Added Successfully')
Custom Directives
=================
-Create custom directives to attach custom behavior to elements in the DOM.
-@Directive decorator is used to create a custom Directive.
-directives won't have templates, whereas components have templates.
-@HostBinding - when a directive wants to Set any property on the host element.
-@HostListener - when a directive wants to listen events from the host element.
Component vs Directive
----------------------
-Component has View/Template where as Directives won't have View/Template.
-Components are used to create UI widgets , Directives are used to add behavior to an existing DOM element.
Custom Directive Assignment
============================
1. create a custom directive (zoomout) which scales the element by 150%.
Angular Pipes
=============
-transform strings, currency amounts, dates, and other data for display.
-Pipes are used in template expressions to accept an input value and return a transformed value.
ex: {{ 5000 | currency }} output: $5,000.00
(OR)
<div [innerHTML]='name | lowercase'></div>
-To apply a pipe, use the pipe operator (|) as shown in the above example.
-Angular provides built-in pipes,The following are commonly used built-in pipes for data formatting.
1.lowercase
2.uppercase
3.titlecase
4.currency
5.date
6.number
7.percent
8.json
9.keyvalue - Iterate Object
10.slice
11.async(Observable)
curreny
-------
{{ 5000 | currency}}
{{ 5000 | currency : 'USD' }}
{{ 5000 | currency : 'INR' }}
{{mySal | currency : '€'}}
input | pipeName : arguement
Date
-----
<h5>{{today | date : 'shortDate'}}</h5>
<h5>{{today | date : 'mediumDate'}}</h5>
<h5>{{today | date : 'longDate'}}</h5>
<h5>{{today | date : 'fullDate'}}</h5>
<h4>{{ today | date: "fullTime":"UTC" }}</h4>
decimal/number
-------------
<h4>{{ 12.111222333 | number: "3.2-5" }}</h4>
012.11122
<h4>{{ 12.1 | number: "3.2-5" }}</h4>
o/p:- 012.10
<p>{{0.5 | number:'3.2-5'}} </p>
o/p:- 000.50
Use format '3.2-5' :
minIntegerDigits = 3
minFractionDigits = 2
maxFractionDigits = 5
Percent Pipe
-------------
{{ 2.5 | percent}} o/p- 250%
{{ 2.5 | percent:'2.2-5'}} o/p- 250.00%
{{0.024 | percent}}
keyvalue
--------
@for(entry of user | keyvalue;track $index){
<h5>{{entry.key}}---{{entry.value}}</h5>
}
slice pipe
-----------
-slice pipe can be used with array and string
<h4>{{cars | slice : 2 : 4}}</h4>
<h4>{{myName | slice : 2 : 4}}</h4>
<h4>{{myName | slice : 2 : -1}}</h4>
Custom Pipe
===========
1. ng generate pipe remaining
2. every angular pipe implements PipeTransform Interface
class RemainingPipe implements PipeTransform {
}
3. override transform()
transform(input: any, maxLength = 100) {
return maxLength - input.length;
}
Assignment
==========
1. Create a custom pipe(ordinal) which takes a number as input and returns in ordinal format
input : 21,22,23,24 output : 21st, 22nd , 23rd, 24th
2. create a custom pipe(Roman) which takes a number as input and returns its equivalent roman value
input : 4
output : IV
3. create a custom pipe called 'age' which takes a date as input and returns the age in years.
input : 04-06-2020
output : 4 years old
4. declare an array of employee objects. display them in a table.
create a custom pipe Salutation that will add 'mr. / miss.' before the employee name.
5. declare an array of employee objects. display them in a table.
add a search-box above the table. create a custom-pipe to filter/search employees data.
Pure & Impure Pipe
------------------
-By Default every custom pipe we create is pure pipe.
-A pure pipe's transform() is only called when Angular detects a change in the value or the parameters passed to a pipe.
-An impure pipe's transform() is called for every change detection cycle
no matter whether the value or parameters change.transform() gets called if any variable in the page chages.
-If the pipe has internal state (result depends on state other than its arguments), set pure to false.
In this case, the pipe is invoked on each change-detection cycle, even if the arguments have not changed.
-to make a pipe impure
@Pipe({
name : 'account',
pure : false
})
Use pipes in component file
---------------------------
1. import pipe class to the component
import { UpperCasePipe } from '@angular/common'
2. register that pipe service in component
providers: [UpperCasePipe]
3. inject that service to the component
constructor(private upperCasePipeObj: UpperCasePipe)
4. use the pipe using transform()
this.b = this.upperCasePipeObj.transform(this.a);
Use custom pipes in component file
----------------------------------
1. import pipe class to the component
import { RemainingPipe } from 'src/app/custom-pipes/remaining.pipe';
2. create an instance of that pipe and call transform() with that instance
const pipeObj = new RemainingPipe();
const remainingChar = pipeObj.transform('hello', 100);
console.log(remainingChar);
Component Communication
=======================
parent --> Child
property Binding []
@input() / inputs:[]
child --> parent
event Binding ()
@output / outputs:[]
Sibling --> child1--> parent -->child2
Q.How can we share data between 2 components (Unrelated Components)
1. services
2. Subject / BehaviourSubject
Props Drilling
==============
-Prop drilling is basically a situation when the same data is being sent at almost every level due to requirements in the final level.
-Solution : State management Library (NgRX)
inputs:['title']
set title(){
// setter for title input variable
// this function gets invoked when a new value is assigned to 'title'
}
Child to parent
===============
1. create an EventEmitter Object and emit that event with the data in child component
import { Component, EventEmitter, OnInit } from '@angular/core';
myEvent = new EventEmitter();
sendDataToParent() {
this.myEvent.emit(this.product);
}
2. add that event information in outputs:[] of child component
outputs:['myEvent']
3. add event listener in parent's HTML & TS
<app-child2 (myEvent)="getDataFromChild($event)"></app-child2>
getDataFromChild(data:any){
this.product = data;
}
component lifecycle hooks/method
================================
constructor - ngOnChanges - ngOnInit - ngDoCheck - ngAfterContentInit -
ngAfterContentChecked - ngAfterViewInit - ngAfterViewChecked - ngOnDestroy. (1+8)
afterNextRender(() => {
});
3 steps to use lifecycle hooks, they are:
========================================
1. Import Hook interfaces from '@angular/core' library
ex:- import {onChanges} from '@angular/core'
2. Declare that component/directive and implement lifecycle hook interface
ex: class ChildComponent implements onChanges
{
}
3. write the hook method and define the functionality of that method.
ex: class ChildComponent implements onChange
{
ngOnChanges()
{
//logic
}
}
ex- ngOnChanges() is a method from 'OnChanges' interface
The hooks/lifecycle methods are executed in this order:
--------------------------------------------------------
constructor()
-This is invoked when Angular creates a component or directive by calling new on the class.
-Initialize class variables,dependency Injection.
-No Business Logic should be written in constructor.
ngOnChanges()
-ngOnchanges() will not be invoked if the component doesn't have inputs:[]
-Invoked every time there is a change in one of the input properties of the component.
-inside ngOnchanges() we can access previous and current value of a variable.
ngOnInit()
-Invoked for every component when a component gets Initialized.
-This hook is called only once, after the first ngOnChanges.not after every ngOnchanges()
-Time Consuming Logic goes here. Ex:- API Call
ngDoCheck()
-Invoked when the change detector of the given component is invoked.
-It allows us to implement our own change detection algorithm for the given component.
-useful to detect and act upon the changes that can not be detected by Angular on its own.
-Due to default behavior of angular change detection, ngOnChanges can't detect if someone changes a property of an object or push an item into array ??. So ngDoCheck comes to recuse.
-Detect deep changes like a property change in object or item is pushed into array even without reference change.
-By using ngDoCheck and KeyValueDiffer, you can monitor changes in complex objects that might not be caught by Angular's default change detection mechanism.
ngAfterContentInit()
-Invoked after Angular performs any content projection into the components view
-Runs only once after the first ngDoCheck()
-Use ngAfterContentInit to call something once after all of the content has been initialized
ngAfterContentChecked()
-Invoked each time the content of the given component has been checked by the change detection mechanism of Angular.
-is called after ngAfterContentInit for the first time.
-is called after every subsequent ngDoCheck
ngAfterViewInit()
-Invoked when the components view has been fully initialized.
-this is the best place for DOM manipulation.
-is called once after ngAfterContentChecked.
-ngAfterViewInit() is called after all child components are initialized and checked.
ngAfterViewChecked()
-is called after every subsequent ngAfterContentChecked.
ngOnDestroy()
-This method is invoked just before Angular destroys the component.
-Clean up code. ex:- clearInterval(),clearTimeout(); unsubscribe();
N.p-ngDoCheck and ngOnChanges should not be implemented together on the same component
Angular Change Detection Strategies
====================================
there are 2 change detection strategies:
1. default (CheckAlways)
2. onpush (CheckOnce)
Default:
-------
-Angular runs change detection on all components when any asynchronous events occur.