-
Notifications
You must be signed in to change notification settings - Fork 7
/
pdf.html
2551 lines (2027 loc) · 59.1 KB
/
pdf.html
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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Remark</title>
<style>
@import url(https://fonts.googleapis.com/css?family=Yanone+Kaffeesatz);
@import url(https://fonts.googleapis.com/css?family=Lato:400,700,400italic);
@import url(https://fonts.googleapis.com/css?family=Ubuntu+Mono:400,700,400italic);
body {
font-family: 'Lato';
background-color: #343F68;
}
h1, h2, h3 {
font-family: 'Lato', sans-serif;
font-weight: normal;
}
.remark-code, .remark-inline-code { font-family: 'Ubuntu Mono'; }
.remark-slide-content {
background-color: #343F68;
color: #FF8551;
}
a {
color: #FFDACA;
}
img {
max-width: 570px;
}
</style>
</head>
<body>
<textarea id="source">
# Angular Basic Training - Gofore
- Open slides: [angular-basic-training.herokuapp.com](http://angular-basic-training.herokuapp.com/)
- Open IDE and start local dev server as instructed in [prerequisites](https://github.com/gofore/angular-basic-training/blob/master/setup/README.md)
- If using IntelliJ IDEA, open "Settings" and go to _TypeScript > Code Style > TypeScript_ and set:
- Spaces: Within > "Object literal braces" & "ES6 import/export braces"
- Punctuation: "Use Single quotes in always"
---
## Agenda - Day 1
#### Morning
- Introduction to SPAs
- TypeScript & Tooling
- Angular Fundamentals
#### Afternoon
- Angular Fundamentals (continued)
- Angular Advanced Topics
---
## Agenda - Day 2
#### Morning
- Reactive Programming with Angular
#### Afternoon
- Testing
---
# Introduction to SPAs
- What is a SPA?
- Real-life examples
- Technical overview
---
# What Is a SPA?
- "A single-page application (SPA) is a web application or web site that fits on a single web page with the goal of providing a more fluid user experience similar to a desktop application." - Wikipedia
- Browser fetches executable code that makes asynchronous calls for actual data to be shown
- Data is visualized and/or manipulated and stored back on server asynchronously
---
![SPA flow](spas-tooling-and-typescript/spa-flow.png "SPA flow")
---
# Real-life Examples
- [Google search](http://www.google.com)
- [Facebook](http://facebook.com)
- [Twitter](http://twitter.com)
---
# SPA Frameworks/Libraries
- Backbone.js
- Ember
- Meteor
- AngularJS
- Aurelia
- React
- Vue.js
- Angular
- And so many more...
---
# AngularJS
- Published 2010
- MVC (Model-View-Controller) framework with dependency injection
- Revolutionary on its own time
- Two-way data binding
- Emphasis on testability (decouples DOM manipulation from app logic)
---
# Angular
- Built by around 20 Google developers & lots of open source devs
- Built with TypeScript (ES2015 and Dart versions available)
- Complete rewrite of AngularJS
- Not just another web framework, complete platform
- Also for desktop and mobile development
- [Documentation](https://angular.io/docs/ts/latest/api/)
---
# Angular Release
- Major version every 6 months (April and October)
- Two version deprecation policy
- Even numbers (4, 6, ..) offer LTS (Long-Term Support)
- Releases:
- 2.0.0-beta.0 1/2016
- 2.0.0-rc.0 5/2016
- 2.0.0 9/2016
- 4.0.0 3/2017
- 5.0.0 11/2017
- 6.0.0 4/2018
- More info in [Angular GitHub](https://github.com/angular/angular/blob/master/docs/RELEASE_SCHEDULE.md)
---
# Tooling
- Traditionally web pages have been just static HTML, CSS and maybe some simple JS for dropdowns etc.
- Nowadays massive SPAs require something more advanced and thus the need for tooling
- Some basic needs for tooling:
- Compiling ES2015/TypeScript -> ES5 and LESS/SASS -> CSS
- Combining multiple source files into single bundle file for faster loading
- Running test suites
- Optimizations (minification, Dead code elimination, tree shaking)
---
# JSON
- JavaScript Object Notation (JSON) is a lightweight data-interchange format
- Meant to be easy for both, humans and machines
- Key-value pairs, where values can be any JavaScript primitives (except functions)
```json
{
"name": "John Doe",
"email": "[email protected]",
"friends": [
{"name": "Jane Doe"},
{"name": "John Doe Jr."}
]
}
```
---
# Node.js & npm
- Node.js is JavaScript interpreter built on top of Chrome's V8 JavaScript engine
- Used for running development server, to run tests, to build production-optimized bundle, etc.
- npm (node package manager) is the package manager for Node
- More packages than on any other package manager for any other language: over 270k (May 2016) ([modulecounts.com](http://www.modulecounts.com/))
---
# package.json - project configuration
- Declares dependencies, development-time dependencies and commands available
- Can be generated with `npm init`
```json
{
"name": "Angular basic training",
"author": "Gofore",
"scripts": {
"build": "my-build.sh",
"start": "my-webserver.sh"
},
"dependencies": {
"@angular/core": "2.0.0",
"@angular/forms": "2.0.0",
"@angular/http": "2.0.0"
},
"devDependencies": {
"typescript": "^2.0.0",
"jasmine": "^2.5.0"
}
}
```
---
# Angular CLI
- Command-line interface for Angular development
- Recommended by the core team
- One of the core modules: `@angular/cli`
- Follows Angular core versioning as of _6.0.0_
- Abstracts away the bundling
- Uses Webpack internally
---
# Angular CLI Features
- Generate the project initially
- Run dev server
- Generate modules, components, services, tests, directives
- Generate production build
- Tests
- Update your dependencies
- Supports CSS preprocessors (SASS and LESS)
- Allows third-party generators for Angular CLI projects
---
# Angular CLI Usage
- Generating an app
```shell
ng new PROJECT_NAME
```
- Run development server
```shell
ng serve # Available in localhost:4200
```
- Run tests
```shell
ng test
```
- Generate a component
```shell
ng generate component todos
```
---
# ES2015 (ES6)
- EcmaScript (ES) is the standard for JavaScript
- One of the newer EcmaScript standards
- Published 2015
- Also known as ES6 because last version was ES5
- Provides a lot of improvements for writing JavaScript in scale
- Not supported by older browsers (namely IE11)
---
# ES2015 - Key Features
- `let` and `const` to replace `var`
- Arrow functions
- Multiline strings
- Modules
- Enhancements on basic types such as `includes()` for string and `find()` for array
---
# Let and const
- `const` declares constant **reference** (not constant value)
- `let` declares variable (eg. `let myVar = 'asd';`)
- **Rule of thumb: Always use `const` if possible, `let` otherwise.**
```javascript
const input = [0, 1, 2, 3, 4];
input = []; // Uncaught TypeError: Assignment to constant variable.
input.push(5); // Works, as input is just the reference
```
For immutable objects & arrays there are libraries such as [_Immutable.js_](https://facebook.github.io/immutable-js/).
---
# Arrow functions
- Lexical `this` and more concise syntax
```javascript
// Traditional function
const increase = function (value) {
return value + 1;
};
// Arrow function
const increase = (value) => {
return value + 1;
};
// Parenthesis omitted
const increase = value => {
return value + 1;
};
// Return value without curly braces
const increase = value => value + 1;
```
---
# String Literals
ES5 string:
```javascript
const str = firstName + ' ' + secondName.charAt(0) + '. ' + lastName;
```
ES2015 multiline string with backticks:
```typescript
const str = ´${firstName} ${secondName.charAt(0)}. ${lastName}`;
```
---
# Modules
Allows `import`ing and `export`ing code between files (modules)
_lib.js_
```javascript
export function square(x) {
return x * x;
}
export function squareSum(x, y) {
return Math.sqrt(square(x) + square(y));
}
```
_main.js_
```javascript
import { square, squareSum } from './lib';
console.log(square(11)); // 121
console.log(squareSum(4, 3)); // 5
```
- Importing from npm modules
```javascript
import { Component, Input } from '@angular/core';
```
---
# Array Functions
- `map`, `filter` and `reduce` operate over the array
- `map` creates a new array with the results of calling a provided function on every element in the calling array.
```typescript
const arr = [0, 1, 2, 3];
const result = arr.map(item => item * 2);
// result is [0, 2, 4, 6]
```
- `filter` creates a new array with all elements that pass the test implemented by the provided function.
```typescript
const arr = [0, 1, 2, 3];
const result = arr.filter(item => item < 2);
// result is [0, 1]
```
- `reduce` applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
```typescript
const arr = [0, 1, 2, 3];
const result = arr.reduce((acc, item) => acc + item , 0);
// result is 6
```
---
# TypeScript
- General-purpose programming language
- Built by Microsoft to build JavaScript in scale
- Initial release in October 2012
- Typed superset of JavaScript -> Any valid JS is valid TypeScript
- Advantages:
- Static type system on top of JavaScript to catch errors already on compile-time
- Angular & RxJS are written in TypeScript
---
# Typing
- Provides the same types as in JavaScript: `number`, `string`, `boolean`, `null`, `undefined` and `object`
- Arrays like `number[]`, `string[]` and `any[]`
- Also some "extra" types such as `any`, `void` and `enum`
- `any` is basically anything like `number`, `string` or `any[]`
- Types are marked after the name
- Type declaration can be omitted when assigning
- Examples:
```typescript
let luckyNumber: number = 50;
luckyNumber = 'nine'; // TypeError: Can't assign string to number
function increase(value: number): number {
return value + 1;
}
```
---
# Interfaces
- Interfaces to declare the acceptable object structures
- Can have optional properties (declared with `?` before `:`)
- _Structural typing_ instead of _Nominal typing_
```typescript
interface Person {
firstName: string;
middleName?: string;
lastName: string;
}
const greeter = (person: Person): string => "Hello, " + person.firstName + " " + person.lastName;
greeter({ firstName: "John", lastName: "Doe" }); // Hello, John Doe
```
---
# Classes
- Like in many other programming languages
- Member fields can be declared in constructor with visibility modifier (`private`, `protected`, `public`)
```typescript
class Student {
fullName: string;
constructor(private firstName: string, private lastName: string) {
this.fullName = this.firstName + " " + this.lastName;
}
getFirstName() {
return this.firstName;
}
}
const student = new Student("John", "Doe");
console.log(student.getFirstName());
```
---
# Annotations (Decorators)
- Used to "decorate" classes and properties with additional functionality
- Like Java annotations
- Apply to next entity (class, field, method) after them
```typescript
@Component({
template: 'my template'
})
class MyClass {
@Input() myProperty: string;
}
```
---
# Angular Fundamentals
- npm Modules
- File Structure
- Architecture
- NgModules
- Components
- Templates
- Component Lifecycle Hooks
- Two-way Data Binding
- Services
- Asynchronous and Server-side Communication
---
# Angular npm Modules
- Framework code is distributed as npm modules:
- `@angular/animations`: Advanced animations functionality
- `@angular/common`: Common utilities (pipes, structural directives etc.)
- `@angular/compiler`: Ahead-of-Time compiler
- `@angular/core`: Core functionality (always needed)
- `@angular/forms`: Form handling
- `@angular/language-service`: Language service for Angular templates for better IDE support
- `@angular/platform-*`: Platform-specific modules (platforms: browser, server, webworker)
- `@angular/router`: Routing functionality
- `@angular/service-worker`: Service worker functionality
- `@angular/upgrade`: NgUpgrade to upgrade from AngularJS -> Angular
- `@angular/http`: Deprecated HTTP client
---
# Coding Style
- [Angular style guide](https://angular.io/styleguide) declares set of rules
- [Codelyzer](https://github.com/mgechev/codelyzer) (TSLint plugin) checks for
- File naming **_name.type.filetype_**:
- _app.module.ts_
- _todos.component.ts_
- _todos.component.html_
- _todos.component.scss_
- _user.service.ts_
- _json.pipe.ts_
---
# Architecture
- App needs to have at least one **module**
- Module has one root **component**
- Component can have child components
---
# NgModules
- Each application has single root _NgModule_
- _NgModule_ is a class with `@NgModule` annotation
- Declares collection of related elements (components, services etc.)
_app.module.ts_
```typescript
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 { }
```
---
# NgModules - Details
- `declarations` contains list of application build blocks, such as components, pipes and directives, with certain selector
- `imports` allows importing of other _NgModules_
- For example `BrowserModule` imports browser-specific renderers and core directives such as `ngFor` and `ngIf`
- `exports` allows declaring what is exported from this module (covered later)
- `providers` contains list of services for dependency injection
- `bootstrap` contains root element(s) for the application (usually named `AppComponent`)
---
# Booting the application
- We need to tell Angular to start our application
- This is done by providing root module `bootstrapModule`
- This will go through the `bootstrap` array and checks for those selectors in HTML
_main.ts_
```typescript
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
platformBrowserDynamic().bootstrapModule(AppModule);
```
_index.html_
```html
<html>
<body>
<app-root></app-root>
</body>
</html>
```
---
# Modules in Large Applications
- Modules are meant to offer possibility to divide the functionality in logical modules
- For example one could have `CustomerModule`, `AdminModule` and `BillingModule`
- To access `exports` of another module, it needs to be `imported` to the module:
_app.module.ts_
```typescript
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
*import { HttpClientModule } from '@angular/common';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule, `HttpClientModule`],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
```
---
# Exporting
- Exporting allows declaring the public API provided by the module
- Consider company-specific UI module where `ListComponent` utilizes `ListRowComponent`:
_ui.module.ts_
```typescript
import { NgModule } from '@angular/core';
import { ListComponent } from './list.component';
import { ListRowComponent } from './list-row.component';
@NgModule({
declarations: [ListComponent, ListRowComponent],
imports: [],
exports: [ListComponent],
providers: []
})
export class UiModule { }
```
---
# Modules as Exports
- Directives `ngIf` and `ngFor` are defined actually in `CommonModule`
- But that is not imported anywhere?
- Actually, `BrowserModule` is exporting `CommonModule` as seen in [source](https://github.com/angular/angular/blob/5.2.9/packages/platform-browser/src/browser.ts#L89)
- -> Modules can be exported as part of module
- If `ListModule` and `TableModule` were separate modules:
_ui.module.ts_
```typescript
import { NgModule } from '@angular/core';
import { ListModule } from './list.module';
import { TableModule } from './table.module';
@NgModule({
declarations: [],
imports: [],
exports: [ListModule, TableModule],
providers: []
})
export class UiModule { }
```
---
# Components
- Build blocks of application UI
- Has a template that it binds data to
- Can contain other components
- Class with `@Component` annotation
_todos.component.ts_
```typescript
import { Component } from '@angular/core';
@Component({})
class TodosComponent { }
```
---
# Components
- Two parameters are mandatory for `@Component` annotation:
- template with `template` (inline template) or `templateUrl` (separate file)
- selector (should always start with application specific prefix like the default: `app`)
- Components need to be declared in NgModule's declarations to be available in templates
_todos.component.ts_
```typescript
import { Component } from '@angular/core';
@Component({
`templateUrl: 'todos.component.html'`,
`selector: 'app-todos'`
})
class TodosComponent { }
```
_app.module.ts_
```typescript
@NgModule({
declarations: [AppComponent, `TodosComponent`]
...
})
export class AppModule { }
```
---
# Generating a Component
Browse to root of the project and run:
```shell
ng generate component todos
```
or abbreviated one:
```shell
ng g c todos
```
This will:
- Create a folder called `todos` with the component, template, styles and test file
- Add the component to `declarations` of your `AppModule`
---
# Templates
- Plain HTML with few Angular specific additions*
_todos.component.html_
```html
<h1>My todo application</h1>
```
- Selectors can be used to add other components
_app.component.html_
```html
<h2>Todos</h2>
<app-todos></app-todos>
```
---
# Tree Structure
- Including components in templates causes tree-like structure
---
# Angular Template Syntax
- **Data binding** with _property name_ inside _double curly braces ({{}})_
```typescript
{{property}}
```
- **Structural directives** with _asterisk ( * ) followed by directive name_
```html
<div *ngIf="showItem">Item</div>
```
- **Attribute binding** with _attribute name_ inside _square brackets ([])_
```typescript
<input [disabled]="property" />
```
- **Event binding** with _event name_ inside _parenthesis_
```typescript
<div (click)="clickHandler()"></div>
```
- **Template local variables** with _hash (#) followed by name_
```typescript
<input #nameInput />
```
---
# Data Binding
Bind property from the component to the template
_app.component.ts_
```typescript
import { Component } from '@angular/core';
@Component({
selector: 'app-component',
templateUrl: 'app.component.html'
})
class AppComponent {
`title: string = 'app works!';`
}
```
_app.component.html_
```html
<h1>`{{title}}`</h1>
```
---
# Structural Directives
- Modify the *structure* of the template
- Two most used are `*ngIf` and `*ngFor`
_todos.component.ts_
```typescript
import { Component } from '@angular/core';
@Component({
selector: 'app-todos',
templateUrl: 'todos.component.html'
})
class TodosComponent {
`todos: any[] = [{name: 'Do the laundry'}, {name: 'Clean my room'}];`
}
```
_todos.component.html_
```html
<div `*ngFor="let todo of todos"`>
{{todo.name}}
</div>
```
---
# Attribute Binding
Bind value from component into HTML attribute
_app.component.ts_
```typescript
import { Component } from '@angular/core';
@Component({
selector: 'app-component',
templateUrl: 'app.component.html'
})
class AppComponent {
`isDisabled: boolean = true;`
}
```
_app.component.html_
```html
<input [disabled]="isDisabled" />
```
---
# Special Attribute Bindings
- Classes and styles have special syntax available:
```html
<div [class.active]="isActive"></div>
<div [style.display]="isShown ? 'block' : 'none'"></div>
```
---
# Attribute Binding for Components
- Attribute binding only works for native properties of HTML elements by default
- Same concept can also be used to pass data from parent component to child component
_parent.component.html_
```html
<app-child `[foo]="todo"`></app-child>
```
_child.component.ts_
```typescript
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child'
})
class ChildComponent {
* @Input()
* foo: string;
}
```
---
# Event Binding
- Register handler code for events
- The actual event can be referenced with `$event`
- The events are basic [DOM events](https://www.w3schools.com/jsref/dom_obj_event.asp) (like `click`, `mouseover`, `change` and `input`)
_todos.component.html_
```html
<input type="text" `(change)="handleChanged($event.target.value)"`></input>
```
_todos.component.ts_
```typescript
import { Component } from '@angular/core';
@Component({..})
class TodosComponent {
* handleChanged(value: string) {
* // Do something with value
* }
}
```
---
# Event Binding for Components
- Event binding only works for native events of HTML elements by default
- Same concept can also be used to pass data from child component to parent component
_parent.component.html_
```html
<app-child `(change)="todo"`></app-child>
```
_child.component.ts_
```typescript
import { Component, Output } from '@angular/core';
@Component({
selector: 'app-child'
})
class ChildComponent {
* @Output()
* change = new EventEmitter<string>();
}
```
---
# Two-way Data Binding
- Two-way data binding with `ngModel` inside _banana-box syntax_: `[(ngModel)]`
- Data flow is still unidirectional, though:
- value from component is updated to input on change
- when user modifies the value, it is updated to component
```html
Name: <input type="text" `[(ngModel)]="name"` />
```
which is just sugar for
```html
Name: <input type="text" `[ngModel]="name" (ngModelChange)="name = $event"` />
```
---
# CSS Encapsulation
- Component can have styles applied:
- Inline in annotation (field `styles` in `@Component`)
- In external files (field `styleUrls`)
- These styles are scoped for component -> No other component can get affected by them
_todos.component.html_
```html
<div class="todos"></div>
```
_todos.component.css_
```css
.todos {
background-color: red;
}
```
Does not affect styles here:
_clients.component.html _
```html
<div class="todos"></div>
```
---
# Components - Inline Styles
_todos.component.ts_
```typescript
import { Component } from '@angular/core';
@Component({
selector: 'app-todos',
templateUrl: 'todos.component.html',
`styles: ['.active-todo { background-color: yellow; }']`
})
class TodosComponent {
}
```
---
# Components - Styles From File
_todos.component.ts_
```typescript
import { Component } from '@angular/core';
@Component({
selector: 'app-todos',
templateUrl: 'todos.component.html',
`styleUrls: ['todos.component.css']`
})
class TodosComponent {
}
```
---
# Component Lifecycle Hooks
- For hooking into certain lifecycle events
- Interface for each hook
- Example hooks: `ngOnInit` (interface `OnInit`), `ngOnChanges` (interface `OnChanges`) and `ngOnDestroy` (interface `OnDestroy`)
```typescript
import { Component, OnInit } from '@angular/core';
export class MyComponent `implements OnInit` {
`ngOnInit() { ... }`
}
```