Noteathon / Angular

Angular

March 4, 2023


Angular - Notes


About

  • Angular is a JS framework, which allows you to create Single Page applications (SPA’s).
  • Installation
      # To install node js
      brew install node
      # check the verison
      node --version
      # Install angular
      sudo npm install -g @angular/cli
      #check the angular version
      ng version
        
      # Create Angular project
      mkdir angular_project
      cd angular_project
      # Setup Angular inside the folder
      ng new my-first-angular-app --no-stric
    

Type Script

  • As the name suggests it is related to TYPE_CHECKING, which is STATIC. JS is DYNAMIC.
  • It is similar to other OOPS langs.
  • Some features
    • Generics
    • Classes, Intefaces
    • Multidata types using Union operator, like Strings, numbers in one function.

Angular

Below are different sections

Styling

  • Adding bootstrap locally to the package : npm install –save bootstrap@3
  • Add the bootstrap css file from node_modules to the angular.json css file.
    "styles": [
                "node_modules/bootstrap/dist/css/bootstrap.min.css",
                "src/styles.css"
              ]
    
  • Check the sources and style.css file to know if the bootstrap min css is imported

Creating a component

  • Step 1 : Create folder with the component name and 3 files
    • server.component.ts
    • server.component.html
    • server.component.css
  • Step 2 : In the TS file, import the component
    • Selector : You can omit the selector, which you can add later, but there should be a template present. Alternatively, we can write template : of different selector present. Supports multiline too. You can also write selectors of different kind like class, tag but not id, hover. Depends on use case, you want to use class type so that you can style too.
    • CSS : add the component css in the URL’s. Can use styleURLs or styles : [h3{color:red}]
      import { Component } from "@angular/core";
    
      @Component({
          selector:'app-server',
          templateUrl:'./server.component.html',
          styleUrls: ['./server.component.css']
      })
    
      export class ServerComponent{
            
      }
    
  • Step 3 : Configure the app.module.ts Register and import ServerComponent in the app.module.ts
      import { ServerComponent } from './server/server.component';
    
      @NgModule({
      declarations: [
          AppComponent,
          ServerComponent
      ],
      imports: [
          BrowserModule,
          FormsModule
      ],
      providers: [],
      bootstrap: [AppComponent]
      })
      export class AppModule { }
    
  • Step 4: Adding the custom component to the app component html file. Since we define on top .ts file selector:'app-server',, we will use same name ```html

```

  • Note :
    • We can use the CLI to do work for us. Either we can use ng generate component servers or ng g c servers to generate the component, perform all the above steps.
    • Use ng g c servers --spec false to ignore the test file
    • Use ng g c servers/server1 --spec false to place server1 component inside the servers folder

Data binding

There are 4 types of binding

  • String Interpolation : Wrap brackets around the variable ``````
  • Property biding : Bind the property of the DOM element. [disabled]="user_name === ''"
  • Event Binding : Bind the events of DOM. Resetting the username (click)="user_name = ''"
  • Two binding : Example is below where you bind the element like Button which depends on the user_name input size.

     <input type="input" [(ngModel)]="name" placeholder="username">
     <p>Entered username : </p>
     <br>
     <br>
     <button type="button" class="btn btn-primary" [disabled]="name === ''" (click)="name = ''">Reset Username</button>
    

Directives

  • Directives are classes that add additional behaviour to the elements. There are 3 types
    • Components : Used with a template. This type of directive is the most common directive type.
    • Attribute directives : Change the appearance or behavior of an element, component, or another directive. - Just affects the properties
    • Structural directives : Change the DOM layout by adding and removing DOM elements.
    • In the below example, we can see *ngIf will toggle the visibility of the block of the element. [ngClass] will set the class value if the value is true.
    • For more info Read here ```html <button type=”button” class=”btn btn-primary” (click)=”incrementCount()”>Display details me</button>

    <p [ngStyle]=”{‘color’: getClickColor()}”> Click count : </p> <p *ngIf=”clickCount%2===0”> Secret Password = “Tuna”</p>

    <p *ngFor=”let logItem of logArr; let i = index” [ngStyle]=”{backgroundColor : i >=4 ? ‘green’ : ‘orange’}” [ngClass]=”{‘white-text’ : i >= 4}”> </p> ```

Components - Databinding and communication

  • Game Controller that emits the value every second

      // Emit Intervals, which can be listened from outside the component
      @Output() intervalFired = new EventEmitter<number>();
    
      lastCount = 0;
      intervalId;
      onStartGame() {
          this.intervalId = setInterval(()=>{
          this.intervalFired.emit(this.lastCount+1);
          this.lastCount++;
          },1000);
      }
    
      onStopGame() {
    
          clearInterval(this.intervalId)
      }
    
  • Root App Component that take the output and send the input to the below Input component
      <div class="container">
          <div class="row">
          <div class="cols-xs-12">
          <h3>Game Controller - communication and Binding</h3>
          <hr>
          <app-game-controller (intervalFired)="onIntervalFired($event)"></app-game-controller>
          <div class="row">
          <div class="col-xs-6">
              <app-odd-game *ngFor="let oddNumber of oddNumbers" [oddNumberVal] = "oddNumber"></app-odd-game>
          </div>
          <div class="col-xs-6">
              <app-even-game *ngFor="let evenNumber of evenNumbers" [evenNumberVal] = "evenNumber"></app-even-game>
          </div>
          </div>
          </div>
          </div>
      </div>
    
  • Odd/Even component that take the input
      export class OddGameComponent {
          @Input() oddNumberVal: number;
      }
    
      export class EvenGameComponent {
          @Input() evenNumberVal: number
      }
    

Debugging

Chrome developer tools > Source Map > Can access in web pack too

Services

  • Declare to be done like service_name.service.ts. Placement is heirarchial, to maintain only 1 instance of the service. Place it in providers of app.module.ts file.
  • Use @Injectable to embed another service into another.
  • HTML
      <h3>Active Users</h3>
      <ul class="list-group">
          <li
              class="list-group-item"
              *ngFor="let user of users; let i = index">
               | <a href="#" (click)="onSetToInactive(i)">Set to Inactive</a>
          </li>
      </ul>
    
  • .TS file
      import { Component, OnInit } from '@angular/core';
    
      import { UserService } from '../users.service';
    
      @Component({
      selector: 'app-active-users',
      templateUrl: './active-users.component.html',
      styleUrls: ['./active-users.component.css']
      })
    
      export class ActiveUsersComponent implements OnInit {
          users: string[];
    
          constructor(private userService: UserService) {}
    
          ngOnInit() {
              this.users = this.userService.activeUsers;
          }
    
          onSetToInactive(id: number) {
              this.userService.setToInactive(id);
          }
      }
    
  • SERVICE with Injectable
      import { Injectable } from '@angular/core';
    
      import { CounterService } from './counter.service';
    
      @Injectable()
      export class UserService {
          activeUsers = ['Max', 'Anna'];
          inactiveUsers = ['Chris', 'Manu'];
    
          constructor(private counterService: CounterService) {}
    
          setToActive(id: number) {
              this.activeUsers.push(this.inactiveUsers[id]);
              this.inactiveUsers.splice(id, 1);
              this.counterService.incrementInActiveToActive();
          }
    
          setToInactive(id: number) {
              this.inactiveUsers.push(this.activeUsers[id]);
              this.activeUsers.splice(id, 1);
              this.counterService.incrementActiveToInactive();
          }
      }
    

RXJS

  • Follows the observable <-> observer pattern.
  • Install npm install --save rxjs@6 and rxjs-compat package: npm install --save rxjs-compat

  • Notes

References

Next: Algorithms