{{ description }}
16 | ``` 17 | 18 | ### Property Binding `[ ]` 19 | 20 | Property Binding allows you to assign model property values to HTML element attributes. 21 | 22 | Example: 23 | 24 | ```html 25 | 26 | ``` 27 | 28 | ### Event Binding `( )` 29 | 30 | Event Binding allows you to bind events (such as clicks, mouseover, etc.) to component model methods. 31 | 32 | Example: 33 | ```html 34 | 35 | ``` 36 | 37 | ### Two-Way Binding `[( )]` 38 | 39 | Two-Way Binding combines *Property Binding* and *Event Binding*. It maintains bidirectional synchronization between the model and the template. Any model or template changes will automatically reflect in the other. 40 | 41 | Example: 42 | ```html 43 | 44 |Hello, {{ name }}!
45 | ``` 46 | 47 | **How to enable Two-Way Binding?** 48 | 49 | To use *Two-Way Binding*, import the **FormsModule** in your main module (usually *app.module.ts*). Make sure the import is correctly included in the imports array of the NgModule: 50 | 51 | ```typescript 52 | import { NgModule } from '@angular/core'; 53 | import { BrowserModule } from '@angular/platform-browser'; 54 | import { FormsModule } from '@angular/forms'; // Import FormsModule 55 | 56 | import { AppComponent } from './app.component'; 57 | 58 | @NgModule({ 59 | declarations: [AppComponent], 60 | imports: [BrowserModule, FormsModule], // Add FormsModule here 61 | providers: [], 62 | bootstrap: [AppComponent], 63 | }) 64 | export class AppModule {} 65 | ``` 66 | 67 | **Data Binding Notes** 68 | 69 | - Data Binding is a powerful way to connect model data and the template, making the application more dynamic and responsive to changes in the data. 70 | - It is important to be cautious to avoid infinite update loops when using Two-Way Binding, as changes in the model can trigger continuous updates in the template and vice versa. 71 | - When using Two-Way Binding with the ngModel directive, remember to import FormsModule as explained earlier. 72 | 73 | ### Resume 74 | 75 | Angular Data Binding is one of the main reasons the framework is so efficient for developing reactive and interactive web applications. 76 | 77 | With Data Binding, you can create dynamic and responsive user interfaces, making it easier for users to interact with your application. 78 | 79 | ## Angular Class and Style Binding 80 | 81 | In addition to the four main types of data binding mentioned earlier, Angular provides additional features to bind CSS classes and styles directly to the template. 82 | 83 | These features are known as **Class Binding** and **Style Binding**. 84 | 85 | ### Class Binding 86 | 87 | **Class Binding** allows you to dynamically add or remove CSS classes to HTML elements based on model property values. This is useful when you want to change the style of an element based on certain conditions or states of the application. 88 | 89 | Example: 90 | 91 | ```html 92 | 93 | ``` 94 | 95 | In this example, the CSS class **"button-new"** will be added to the button only when the **isNew** property in the component is true. 96 | 97 | ### Style Binding 98 | 99 | Style Binding lets you set CSS styles directly in the template based on model property values. This lets you dynamically change style properties like color, size, margins, etc. 100 | 101 | Example: 102 | 103 | ```html 104 |This text has a dynamic color
105 | ``` 106 | 107 | In this example, the paragraph's **color** CSS style will be set based on the value of the **corTexto** property in the component. 108 | 109 | **Applying Conditions with Class and Style Binding** 110 | 111 | In addition to adding classes and styles, you can apply complex conditions using **ternary expressions** or the **&&** (AND) operator to combine multiple conditions. 112 | 113 | Example using ternary expression: 114 | 115 | ```html 116 | 117 | ``` 118 | 119 | Example using the && (AND) operator: 120 | 121 | ```html 122 | 123 | ``` 124 | 125 | **Class and Style Binding in Two-Way Binding** 126 | 127 | Combining Class Binding or Style Binding with Two-Way Binding creates highly dynamic and interactive user interfaces. 128 | 129 | Example with Two-Way Binding and Class Binding: 130 | 131 | ```html 132 | 133 | ``` 134 | 135 | In this example, the value of the `classCSS` property in the model is bound to the class attribute of the input element, allowing the user to change the applied CSS class dynamically. 136 | 137 | *Summary* 138 | 139 | Class Binding and Style Binding are powerful Angular features for dynamically applying styles and classes in the template based on model properties. These functionalities make developing interactive and reactive user interfaces easier and more efficient, allowing you to create more dynamic applications with a better user experience. 140 | 141 | 142 | ## 👷 Task 143 | 144 | Create pull requests for your project according to [Task Submission Guidelines.](../assessment.md#task-submission) 145 | 146 | - Create an angular project in Github. 147 | - Include a devcontainer to work with typescript. You can use [Ria Angular Example](https://github.com/persapiens-classes/ifrn-angular-ria-angular-example). 148 | - Create an insert, list, and remove crud operations of a model in the template. Your model should have 3 attributes: string, number, and boolean. 149 | -------------------------------------------------------------------------------- /class/4-angular/18-http-client.md: -------------------------------------------------------------------------------- 1 | ## HttpClient 2 | 3 | **What is HttpClient?** 4 | 5 | - The *HttpClient* is an Angular module that provides an easy way to make HTTP requests in Angular applications. 6 | - It is a class that is part of the *@angular/common/http* module. 7 | 8 | **Why is it important?** 9 | 10 | - Many web applications need to interact with servers to fetch or send data. The *HttpClient* makes this possible efficiently and in an organized manner. 11 | - It handles low-level details, such as creating and managing HTTP requests and responses. 12 | 13 | **How does it fit into Web Development?** 14 | 15 | - The *HttpClient* is used to communicate with RESTful APIs, web services, and other HTTP resources. 16 | - It is an essential part of front-end development when you need to fetch data from or update data on a server. 17 | 18 | **Basic HttpClient Configuration** 19 | 20 | ```typescript 21 | import { HttpClient } from '@angular/common/http'; 22 | 23 | constructor(private http: HttpClient) { } 24 | ``` 25 | 26 | - To use HttpClient, first import it from the **@angular/common/http** module. 27 | - Then, inject it as a dependency in the constructor of a component or service. 28 | - Now you can use *this.http* to make HTTP requests in your application. 29 | 30 | See [Angular HttpClient Official Reference.](https://angular.dev/guide/http) 31 | 32 | 33 | --- 34 | 35 | ## HttpClient and RxJS 36 | 37 | RxJS is a JavaScript library that has become one of the fundamental pillars in modern web application development, especially in reactive and asynchronous environments. 38 | 39 | Here are some key concepts related to RxJS: 40 | 41 | 1. **Observables**: Observables are at the core of RxJS. They represent a data source that can emit values over time. These values can be DOM events, API responses, user clicks, or anything else you want to observe. 42 | 43 | 2. **Operators**: Operators are functions that allow you to transform, filter, combine, and manipulate the data that flows through an Observable. There are many available operators, such as **map**, **filter**, **merge**, **concat**, and many others. 44 | 45 | 3. **Subscriptions**: A Subscription is an object that represents the execution of an Observable and allows you to unsubscribe from it when it's no longer needed. This is important to prevent memory leaks. 46 | 47 | 4. **Observers**: Observers are the consumers of Observables. They define what to do when an Observable emits values, usually in the form of functions that handle those values. 48 | 49 | 5. **Asynchronous Data Flow**: RxJS is especially useful when working with asynchronous operations, such as API requests, DOM events, or anything not directly controlled by your code. 50 | 51 | 6. **Reactive Programming**: Reactive programming is a programming paradigm that focuses on the propagation of state changes. With RxJS, you can create reactive data pipelines that automatically respond to data changes. 52 | 53 | 7. **Cross-Platform Compatibility**: RxJS is a JavaScript library, but its ideas and concepts can be applied in many programming languages. There are Rx implementations in other languages, such as RxJava for Java and RxSwift for Swift. 54 | 55 | HttpClient and RxJS have a close relationship in the context of Angular application development. 56 | See [Angular Making HTTP requests.](https://angular.dev/guide/http/making-requests) 57 | 58 | - **Observables in HttpClient**: HttpClient uses **RxJS** Observables to handle HTTP requests and responses in an asynchronous and reactive way. When you make an HTTP request using HttpClient, it returns an Observable that you can subscribe to in order to receive the results. 59 | 60 | - **Handling Asynchronous Responses**: HTTP requests are asynchronous operations, since you're waiting for a response from the server. **RxJS** is a library that efficiently handles asynchronous data streams and events. Therefore, HttpClient uses RxJS Observables to handle these responses reactively. 61 | 62 | - **RxJS Operators with HttpClient**: You can use RxJS operators alongside HttpClient to manipulate and transform response data. For example, you can use the **map** operator to transform the response data before processing it, or use the **catchError** operator to handle request errors. 63 | 64 | ### Getting Data via REST API (HTTP GET) 65 | 66 | - Retrieving data from a server 67 | - Using the **.get()** method 68 | 69 | ```typescript 70 | this.http.get('https://api.example.com/data').subscribe(data => { 71 | console.log(data); 72 | }); 73 | ``` 74 | 75 | ### Updating Data via REST API (HTTP PUT) 76 | 77 | - Updating data on the server 78 | - Using the **.put()** method 79 | 80 | ```typescript 81 | const newData = { name: 'New Name', age: 25 }; 82 | this.http.put('https://api.example.com/data/1', newData).subscribe(response => { 83 | console.log(response); 84 | }); 85 | ``` 86 | 87 | ### Deleting Data via REST API (HTTP DELETE) 88 | 89 | - Deleting data on the server 90 | - Using the **.delete()** method 91 | 92 | ```typescript 93 | this.http.delete('https://api.example.com/data/1').subscribe(response => { 94 | console.log(response); 95 | }); 96 | ``` 97 | 98 | ### Inserting New Data via REST API (HTTP POST) 99 | 100 | - Sending new data to the server 101 | - Using the **.post()** method 102 | 103 | ```typescript 104 | const newData = { name: 'New Name', age: 25 }; 105 | this.http.post('https://api.example.com/data', newData).subscribe(response => { 106 | console.log(response); 107 | }); 108 | ``` 109 | 110 | ## Handling Errors 111 | 112 | - Error handling with *catchError* 113 | - Example of error handling 114 | 115 | ```typescript 116 | this.http.get('https://api.example.com/data').pipe( 117 | catchError(error => { 118 | console.error('Error:', error); 119 | return throwError(() => new Error('Something went wrong.')); 120 | }) 121 | ).subscribe(data => { 122 | console.log(data); 123 | }); 124 | ``` 125 | 126 | --- 127 | 128 | ## 👷 Task 129 | 130 | Create pull requests for your project according to [Task Submission Guidelines.](../assessment.md#task-submission) 131 | 132 | - Create Auth service to sign in some backend system, keeping jwt token in localStorage. 133 | - Create Login component to sign in using Auth service. Refactor routers to do login as initial page. 134 | - Using authentication token, protect routers to other componentes with [Angular Guard](https://angular.dev/api/router/CanActivate). 135 | - Create model service using httpClient to do CRUD options in backend system, adding jwt token with [Angular Http Interceptors](https://angular.dev/guide/http/interceptors). 136 | 137 | You can use tasks [Create Auth Service to sign in Account Backend](https://github.com/persapiens-classes/account-frontend/issues/18), [Create Login Component using sign in of AuthService](https://github.com/persapiens-classes/account-frontend/issues/20), [Protect routers to other components with Angular Guard (Authenticated User) ](https://github.com/persapiens-classes/account-frontend/issues/22), [Create owner service using httpclient to do crud options in account backend system](https://github.com/persapiens-classes/account-frontend/issues/25) of the Account Frontend. 138 | -------------------------------------------------------------------------------- /class/4-angular/13-components.md: -------------------------------------------------------------------------------- 1 | ### **Angular Components** 2 | 3 | Components are essential building blocks of Angular. They play a central role in the framework's architecture, enabling you to create reusable and independent parts of the user interface, each with its own logic, template, and style. 4 | 5 | --- 6 | 7 | ### **Creating a Component** 8 | 9 | To create a new component, you can use the Angular CLI (Command Line Interface) with the following command: 10 | 11 | ```bash 12 | ng generate component component-name 13 | ``` 14 | 15 | This will generate a file structure for the new component, including a **.ts** file (component logic), **.html** file (template), and **.css** file (styles), among others. 16 | 17 | --- 18 | 19 | **Structure of a Component:** 20 | 21 | An Angular component consists of three main parts: 22 | 23 | - the @Component decorator 24 | - the component class 25 | - the associated template. 26 | 27 | **Example:** 28 | 29 | ```typescript 30 | import { Component } from "@angular/core"; 31 | 32 | @Component({ 33 | selector: "app-example", // Component selector used in the template. 34 | templateUrl: "./example.component.html", // Path to the component's template. 35 | styleUrls: ["./example.component.scss"], // Component's style files. 36 | }) 37 | export class ExampleComponent { 38 | // Component logic here... 39 | } 40 | ``` 41 | 42 | --- 43 | 44 | **Using a Component:** 45 | 46 | You can use a component within other components or templates by referencing the selector defined in the @Component decorator. 47 | 48 | **Example of Using a Component:** 49 | 50 | ```html 51 |{{ message }}
", 72 | }) 73 | export class ChildComponent { 74 | @Input() message: string; 75 | } 76 | ``` 77 | 78 | ```html 79 |{{ message }}
", 144 | }) 145 | export class ExampleComponent implements OnInit { 146 | message: string; 147 | 148 | ngOnInit() { 149 | this.message = "Hello, world!"; 150 | } 151 | } 152 | ``` 153 | 154 | --- 155 | 156 | #### **ngOnChanges** 157 | 158 | The `ngOnChanges` event is triggered whenever an input value (`@Input`) changes. It provides an object containing the detected changes. 159 | 160 | ```typescript 161 | import { Component, Input, OnChanges, SimpleChanges } from "@angular/core"; 162 | 163 | @Component({ 164 | selector: "app-child", 165 | template: "{{ message }}
", 166 | }) 167 | export class ChildComponent implements OnChanges { 168 | @Input() message: string; 169 | 170 | ngOnChanges(changes: SimpleChanges) { 171 | if (changes.message) { 172 | console.log("Message value changed to:", changes.message.currentValue); 173 | } 174 | } 175 | } 176 | ``` 177 | 178 | --- 179 | 180 | #### **ngDoCheck** 181 | 182 | The `ngDoCheck` event is triggered whenever change detection is executed. It can be used to perform manual change checks. 183 | 184 | ```typescript 185 | import { Component, DoCheck } from "@angular/core"; 186 | 187 | @Component({ 188 | selector: "app-example", 189 | template: "{{ counter }}
", 190 | }) 191 | export class ExampleComponent implements DoCheck { 192 | counter: number = 0; 193 | 194 | ngDoCheck() { 195 | console.log("ngDoCheck executed."); 196 | // Logic for manual change detection here... 197 | } 198 | } 199 | ``` 200 | 201 | --- 202 | 203 | #### **ngOnDestroy** 204 | 205 | The `ngOnDestroy` event is triggered when a component is about to be destroyed. It is used to perform cleanup actions, such as canceling subscriptions or disconnecting from services. 206 | 207 | ```typescript 208 | import { Component, OnDestroy } from "@angular/core"; 209 | 210 | @Component({ 211 | selector: "app-example", 212 | template: "Component will be destroyed soon.
", 213 | }) 214 | export class ExampleComponent implements OnDestroy { 215 | ngOnDestroy() { 216 | console.log("Component destroyed."); 217 | // Cleanup actions here... 218 | } 219 | } 220 | ``` 221 | 222 | --- 223 | 224 | **Note:** 225 | 226 | Remember that lifecycle events are optional, and you don't need to implement all of them in every component. Choose the events that are relevant to what you want to achieve and use them as needed. 227 | 228 | In addition to the main Angular lifecycle methods such as `ngOnInit`, `ngOnChanges`, `ngDoCheck`, and `ngOnDestroy`, there are other methods like **ngAfterContentInit**, **ngAfterContentChecked**, **ngAfterViewInit**, and **ngAfterViewChecked** that provide opportunities to interact with projected content and the component's view. Understanding and utilizing these methods appropriately will enable you to control and optimize your component's logic across different lifecycle phases. 229 | 230 | ## 👷 Task 231 | 232 | Create pull requests for your project according to [Task Submission Guidelines.](../assessment.md#task-submission) 233 | 234 | - Refactor that app component of the project in previous task (12-ui-components) to use dedicated insert, update, detail, remove, and list components. 235 | 236 | You can use tasks [Create hello, insert and list components](https://github.com/persapiens-classes/account-frontend/issues/8) and [Improve owner crud](https://github.com/persapiens-classes/account-frontend/issues/10) of Angular Example Project. 237 | -------------------------------------------------------------------------------- /class/4-angular/15-routers.md: -------------------------------------------------------------------------------- 1 | ### **Angular Router** 2 | 3 | Routing is a key part of many modern web applications, enabling users to navigate between different sections of the app without reloading the page. Angular offers a robust routing module that simplifies navigation between components and views. 4 | 5 | --- 6 | 7 | ### **Creating the Routing Module** 8 | 9 | You need to create the routing module, `_AppRoutingModule_`, and define the application's routes in it. If this module was not created during project initialization, execute the following command: 10 | 11 | ```bash 12 | ng generate module app-routing --flat --module=app 13 | ``` 14 | 15 | --- 16 | 17 | ### **Setting Up Routing** 18 | 19 | There are three fundamental steps to creating a route: 20 | 21 | --- 22 | 23 | 1. **Import the Routing Module in the `_app.module.ts_` file** 24 | 25 | Import the **AppRoutingModule** into the **AppModule** and add it to the imports array. 26 | 27 | ```typescript 28 | import { BrowserModule } from '@angular/platform-browser'; 29 | import { NgModule } from '@angular/core'; 30 | import { AppRoutingModule } from './app-routing.module'; // Import AppRoutingModule 31 | import { AppComponent } from './app.component'; 32 | 33 | @NgModule({ 34 | declarations: [AppComponent], 35 | imports: [ 36 | BrowserModule, 37 | AppRoutingModule, // Add AppRoutingModule to the imports array 38 | ], 39 | providers: [], 40 | bootstrap: [AppComponent], 41 | }) 42 | export class AppModule {} 43 | ``` 44 | 45 | --- 46 | 47 | 2. **Import `RouterModule` and `Routes` into your routing module (`_AppRoutingModule_`)** 48 | 49 | ```typescript 50 | import { RouterModule, Routes } from '@angular/router'; // Import RouterModule and Routes 51 | 52 | const routes: Routes = []; // Array of routes 53 | 54 | @NgModule({ 55 | imports: [RouterModule.forRoot(routes)], 56 | exports: [RouterModule], 57 | }) 58 | export class AppRoutingModule {} 59 | ``` 60 | 61 | --- 62 | 63 | 3. **Define routes in the `Routes` array** 64 | 65 | Each route in the array is a JavaScript object with two properties. The first, **path**, defines the URL path for the route. The second, **component**, specifies the Angular component to use for the corresponding path. 66 | 67 | ```typescript 68 | const routes: Routes = [ 69 | { path: '', component: HomeComponent }, 70 | { path: 'about', component: AboutComponent }, 71 | { path: 'contact', component: ContactComponent }, 72 | ]; 73 | ``` 74 | 75 | --- 76 | 77 | ### **Navigating Between Routes** 78 | 79 | Navigation between routes can be achieved using the `_routerLink_` directive in templates or the `_Router_` service in code. 80 | 81 | **Using `routerLink` in a Template** 82 | 83 | ```html 84 | Home 85 | About 86 | Contact 87 | ``` 88 | 89 | **Displaying Routes in the Template** 90 | 91 | ```html 92 |I am an attribute directive
20 | ``` 21 | 22 | ```html 23 | 24 |Attribute Directive - [ngClass]
25 | ``` 26 | 27 | The **NgStyle** and **NgClass** directives are attribute directives used to dynamically alter the style of any DOM element based on a condition. 28 | 29 | [Official Documentation for NgStyle](https://angular.dev/guide/directives#setting-inline-styles-with-ngstyle) 30 | [Official Documentation for NgClass](https://angular.dev/guide/directives#adding-and-removing-classes-with-ngclass) 31 | 32 | ### Structural Directives 33 | 34 | Structural Directives manipulate the DOM structure by adding or removing HTML elements from the template. They are applied as structural attributes on HTML elements. 35 | 36 | #### ngIf Directive 37 | 38 | Example: 39 | 40 | ```html 41 | 42 |You chose option A
99 |You chose option B
100 |You chose option C
101 |Please choose a valid option (A, B, or C).
102 |You chose option 1
114 |You chose option 2
115 |You chose option 3
116 |Please choose a valid option (1, 2, or 3).
117 |This paragraph will be highlighted
190 | ``` 191 | 192 | Here, **'appHighlight'** is a custom Attribute Directive that changes the style of the paragraph when **'highlightText'** is true. 193 | In this example, we created a custom Attribute Directive named **appHighlight**, which highlights the text of the element when the mouse enters its area and removes the highlight when the mouse leaves. 194 | 195 | Use the following command to generate directives: 196 | 197 | ```node 198 | ng generate directive