Giter VIP home page Giter VIP logo

comandos-de-angular's Introduction

Indice

  1. ${\color{#00dbac}Iniciar\space el \space Proyecto}$ 🖲

  • ${\color{#dbac00}Instalar\space Angular\space Material}$ 🖲

  • ${\color{#dbac00}Cambiar\space directorio\space del\space proyecto\space}$ 🖲

  • ${\color{#dbac00}Desistalar\space e\space instalar\space AngularCli\space}$ 🖲

  1. ${\color{#00dbac}Iniciar\space en\space servidor}$🌐

  2. ${\color{#00dbac}Cambiar\space puertos}$⚙️

  3. ${\color{#00dbac}Componentes}$🔧

  • ${\color{#dbac00}Crear\space nuevo\space componente}$🔧
    • ${\color{#db0700}Sin\space tests}$🔧
    • ${\color{#db0700}Sin\space tests\space y \space hoja\space de\space estilos}$🔧
    • ${\color{#db0700}Sin\space template}$🔧
    • ${\color{#db0700}Con\space standalone}$🔧
    • ${\color{#db0700}En\space otro \space directorio}$🔧
    • ${\color{#db0700}Generar\space componente \space dentro\space del\space app-module}$🔧
    • ${\color{#db0700}Generar\space componente \space dentro\space de\space otro\space componente}$🔧
    • ${\color{#db0700}Sin\space importar \space en\space app-module}$🔧
  1. ${\color{#00dbac}Modulos}$🧩

  • ${\color{#dbac00}Crear\space nuevo\space modulo}$🧩

  • ${\color{#dbac00}Especificar\space carpeta\space de\space destino}$🧩

  • ${\color{#dbac00}Crear\space modulo\space con\space enrutamiento}$🧩

  • ${\color{#dbac00}Crear\space componente\space en\space el\space modulo}$🧩

  • ${\color{#dbac00}Crear\space modulo\space con\space \space Lazy\space Loaded}$🧩

  • ${\color{#dbac00}Crear\space modulo\space con\space \space routing\space en\space app}$🧩

  1. ${\color{#00dbac}Servicios}$📡

  • ${\color{#dbac00}Crear\space nuevo\space servicio}$📡
  • ${\color{#dbac00}Ejemplo\space con\space inject\space y \space signal }$📡
  1. ${\color{#00dbac}Routing}$🔗

  • ${\color{#dbac00}Configurar\space Enrutamiento\space}$🔗
  • ${\color{#dbac00}Crear\space rutas\space loadChildren \space children }$🔗
  • ${\color{#dbac00}Configurar\space para\space Angular17}$🔗
  1. ${\color{#00dbac}Guard}$🛡️

  • ${\color{#dbac00}Crear\space guard\space}$🛡️
    • ${\color{#db0700}Crear\space guard\space con\space CanActivate}$🛡️
  1. ${\color{#00dbac}Flat\space}$📁

  2. ${\color{#00dbac}Pipes\space}$🌀

  • ${\color{#dbac00}Crear\space pipes\space}$🌀
  1. ${\color{#00dbac}Popup\space}$💬

  • ${\color{#dbac00}Generar\space Popup}$💬
  1. ${\color{#00dbac}Confirm-box\space}$✔️

  • ${\color{#dbac00}Generar\space Confirm-box}$✔️
  1. ${\color{#00dbac}Directivas\space}$📐

    • ${\color{#dbac00}Directivas\space estructurales\space}$📐

      • ${\color{#db0700}Ejemplos}$📐
    • ${\color{#dbac00}Directivas\space de\space atributo}$📐

      • ${\color{#db0700}Ejemplos}$📐
    • ${\color{#dbac00}Directivas\space de\space eventos}$📐

      • ${\color{#db0700}Ejemplos\space eventos}$📐
        • ${\color{#009ddb}(click)}$📐
        • ${\color{#009ddb}(input)}$📐
        • ${\color{#009ddb}(submit)}$📐
        • ${\color{#009ddb}(mouseout)}$📐
        • ${\color{#009ddb}(keyup)}$📐
        • ${\color{#009ddb}(keydown)}$📐
        • ${\color{#009ddb}(focus)}$📐
        • ${\color{#009ddb}(blur)}$📐
    • ${\color{#dbac00}Directivas\space personalizadas}$📐

    • ${\color{#dbac00}URL\space Event\space Binding }$📐

  2. ${\color{#00dbac}Compilar\space}$🔄

  • ${\color{#dbac00}Modo\space desarrollo\space y\space generar\space dist/ }$🔄
  • ${\color{#dbac00}Modo\space producción}$🔄
  1. ${\color{#00dbac}Interceptor}$🚥

  2. ${\color{#00dbac}Ciclos\space de\space vida}$🌱

  • ${\color{#dbac00}ngOnChanges }$🌱
  • ${\color{#dbac00}ngOnInit }$🌱
  • ${\color{#dbac00}ngDoCheck }$🌱
  • ${\color{#dbac00}ngAfterViewInit }$🌱
  • ${\color{#dbac00}ngOnDestroy }$🌱
  • ${\color{#dbac00}Repo\space LifeCicle}$🌱
  1. ${\color{#00dbac}Crear\space JSON\space Server }$📊

  2. ${\color{#00dbac}URL\space Importantes}$🚀

  • ${\color{#dbac00}Diseño }$🚀
  • ${\color{#dbac00}Tutoriales }$🚀
  • ${\color{#dbac00}APIs }$🚀
  • ${\color{#dbac00}Librerías}$🚀
  • ${\color{#dbac00}HostListener }$🚀
  • ${\color{#dbac00}BD}$🚀
  • ${\color{#dbac00}Instalables}$🚀
  • ${\color{#dbac00}Subir\space Web}$🚀
  • ${\color{#dbac00}NPMjs}$🚀
  • ${\color{#dbac00}FernandoH\space PDF}$🚀
  • ${\color{#dbac00}Repositorios }$🐙
    • ${\color{#009ddb}Traducciones}$🐙
    • ${\color{#009ddb}Formularios}$🐙
  • ${\color{#dbac00}Readme}$🚀
  1. Iniciar el Proyecto

  • ${\color{blue}Modo \space basico }$
ng new nombre-del-proyecto
  • ${\color{blue}Modo \space basico\space blanco }$
ng new nombre-del-proyecto --minimal
  • ${\color{blue}Crear \space con\space tabs }$
ng new nombre-del-proyecto 

Entra al directorio del proyecto:
1º cd nombre-del-proyecto
2º Crea los componentes de pestañas:
ng g c tab1 --skip-tests
ng g c tab2 --skip-tests
ng g c tab2 --skip-tests

  • Configura el enrutamiento:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { Tab1Component } from './tab1/tab1.component';
import { Tab2Component } from './tab2/tab2.component';
import { Tab3Component } from './tab3/tab3.component';

const routes: Routes = [
  { path: 'tab1', component: Tab1Component },
  { path: 'tab2', component: Tab2Component },
  { path: 'tab3', component: Tab3Component },
  { path: '', redirectTo: '/tab1', pathMatch: 'full' }, // Redirige a tab1 por defecto
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
  • Modifica el archivo app.component.html:
<ul>
  <li><a routerLink="/tab1">Tab 1</a></li>
  <li><a routerLink="/tab2">Tab 2</a></li>
  <li><a routerLink="/tab3">Tab 3</a></li>
</ul>
<router-outlet></router-outlet>
  • ${\color{blue}Con \space prefijo \space para \space especificar \space todos \space los \space componentes: }$
ng new nombre-del-proyecto --prefix nombrePrefijo
  • ${\color{blue}Con \space enrutamiento \space y \space utilizando \space SCSS \space en \space su \space totalidad }$
ng new AngularMaterial --routing --style=scss

Instalar Angular Material

  • ${\color{blue}Dentro \space del \space proyecto}$
ng add @angular/material

Cambiar directorio del proyecto

ng new app-name --directory="FOLDER-NAME"

# Ejemplo
ng new myApp --directory="C:\New-Folder\"

Desistalar e instalar AngularCLI

npm uninstall -g @angular/cli
npm cache clean --force
npm install -g @angular/cli@16

${\color{orange}Back\space}$ 🔙

  1. Iniciar en servidor

ng serve -o

o

ng s -o
  • ${\color{blue}Scripts \space package.json\space }$
"scripts": {
    "ng": "ng",
    "envs": "node ./scripts/set-envs.js",
    "start": "npm run envs && ng serve",
    "build": "npm run envs && ng build",
    "watch": "ng build --watch --configuration development",
    "test": "ng test"
}
# se inicia el servidor:
npm start

${\color{orange}Back\space}$ 🔙

  1. Cambiar puertos

ng serve --port 4200

${\color{orange}Back\space}$ 🔙

  1. Componentes

    Crear nuevo componente

ng g c componente-nombre

Sin tests

ng g c componente-nombre --skip-tests

Sin tests y estilos

ng g c nombre-componente --inline-style --skip-tests

Sin template

ng g c mi-carpeta/componente-nombre --inline-template

Con Standalone

ng g c alone/pages/alonePage --standalone --skip-tests

En otro directorio

ng g c mi-carpeta/componente-nombre

Generar componente dentro del app-module

 ng g c components/componente-nombre --module=app.module

Generar componente dentro de otro componente

 ng g c nombre-carpeta(componente)/nuevo-componente

Sin importar en app-module

 ng g c mi-carpeta/componente-nombre --skip-import

${\color{orange}Back\space}$ 🔙

  1. Modulos

    Crear nuevo modulo

     ng g m modulo-nombre
    

    Especificar carpeta de destino

    ng g m mi-carpeta/modulo-nombre
    

    Crear módulo con enrutamiento

     ng g m modulo-nombre --routing
    

    Crear componente en el modulo

    # 1º se debe crear el modulo
    ng g m Nombremodulo --routing
    
    # 2º se crear el componenete con el nombre modulo
    ng g c Nombremodulo/nombre-Componente --flat --skip-tests
    

    Crear modulo con Lazy Loaded

     ng g m products --module app --route products
    

    Crear modulo con routing directorio

    ng g m products --routing --module app
    

${\color{orange}Back\space}$ 🔙

  1. Servicios

    Crear nuevo servicio

     ng g s nuevo-servicio --skip-tests
    

    Ejemplo con inject y signal

Important

URL para enviroments e interfaces 👉 Ejemplo

1º Creamos el servicio:

       import { HttpClient } from '@angular/common/http';
       import { Injectable, inject } from '@angular/core';
       import { Observable, map, tap } from 'rxjs';
       import { SingleUserResponse, User } from '../interfaces/user-request.interface';
       
       @Injectable({
         providedIn: 'root',
       })
       export class UserServicesService {
         private http = inject(HttpClient);
       
         private url = 'https://reqres.in/api/users';
       
         getUserById(id: number): Observable<User> {
           return this.http.get<SingleUserResponse>(`${this.url}/${id}`).pipe(
             map((response) => response.data),
             tap(console.log)
           );
         }
       }

2º Importamos en app.module :

     import { NgModule } from '@angular/core';
     import { BrowserModule } from '@angular/platform-browser';
     
     import { AppRoutingModule } from './app-routing.module';
     import { AppComponent } from './app.component';
     import { HttpClientModule } from '@angular/common/http';
     
     @NgModule({
       declarations: [
         AppComponent
       ],
       imports: [
         BrowserModule,
         AppRoutingModule,
         HttpClientModule
       ],
       providers: [],
       bootstrap: [AppComponent]
     })
     export class AppModule { }

3º Creamos Interfaces:

       // Generated by https://quicktype.io
  
  export interface SingleUserResponse {
    data: User;
    support: Support;
  }
  
  export interface User {
    id: number;
    email: string;
    first_name: string;
    last_name: string;
    avatar: string;
  }
  
  export interface Support {
    url: string;
    text: string;
  }

4º Inyectamos el servicio y usamos el signal en vez del construtor:

  import { User } from '../../interfaces/user-request.interface';
  import { UserServicesService } from './../../services/user-services.service';
  import { Component, OnInit, inject, signal } from '@angular/core';
  
  @Component({
    selector: 'app-user-info-page',
    templateUrl: './user-info-page.component.html',
    styleUrls: ['./user-info-page.component.scss'],
  })
  export class UserInfoPageComponent implements OnInit {
    private UserServices = inject(UserServicesService);
    public userId = signal(1);
    public CurrentUser = signal<User | undefined>(undefined);
    public userWasFound = signal(true);
  
    ngOnInit(): void {
      this.loadUser(this.userId());
    }
  
    loadUser(id: number) {
      if (id <= 0) return;
  
      this.userId.set(id);
      this.CurrentUser.set(undefined)
  
      this.UserServices.getUserById(id).subscribe((user) => {
        this.CurrentUser.set(user);
      });
    }
  }

5º Su llama en html:

      <h1>Informacion del usuario</h1>
 <hr />
 
 <div class="row">
   <div class="col-4">
     <h3>Usuario Actual: {{ userId() }}</h3>
 
     <button (click)="loadUser(userId() - 1)" class="btn btn-primary">
       Anterior
     </button>
     &nbsp;
     <button (click)="loadUser(userId() + 1)" class="btn btn-primary">
       Siguiente
     </button>
     &nbsp;
   </div>
 
   <div class="col-8" *ngIf="CurrentUser()">
     <h3>Usuario: </h3>
     <p>Correo: {{CurrentUser()!.email}}</p>
     <p>Nombre: {{CurrentUser()!.first_name}}</p>
 
     <img [src]="CurrentUser()!.avatar" alt="Avatar" class="rounded-3"/>
   </div>
 
   <div class="col-8 text-danger">
     <h3>Usuario no encontrado</h3>
   </div>
 </div>

${\color{orange}Back\space}$ 🔙

  1. Routing

    Configurar enrutamiento

    # para crear routing dentro de un modulo
     ng g m nombreModuloRouting --flat
    

    Crear rutas loadChildren children

    • En app.routing.module.ts
         const routes: Routes = [
      {
      path: 'products',
      loadChildren: () =>
       import('./products/products.module').then((m) => m.ProductsModule),
      },
      {
      path: 'signals',
      loadChildren: () => import('./signals/signals.module').then(m => m.SignalsModule)
      },
     {
     path: '**',
     redirectTo: 'products',
     },
     ];
    • En otroHijo.routing.module.ts
     const routes: Routes = [
   {
  path: '',
  component: SignalsLayoutComponent,
  children: [
    { path: 'counter', component: CounterComponent },
    { path: 'properties', component: PropertiesPageComponent },
    { path: 'user-info', component: UserInfoPageComponent },
    { path: '**', redirectTo: 'counter' },
    ],
   },
 ];
  • Enrutar con menu

          interface MenuItems {
        title: string;
        router: string;
      }
    
       public mennuItems: MenuItems[] = [
        { title: ' Contador', router: 'Counter' },
        { title: ' Usuarios', router: 'user-info' },
        { title: ' Actualizaciones', router: 'properties' },
      ];
    
      En su html...
    
     <ul class="list-group">
       <li
         *ngFor="let item of mennuItems"
         class="list-group-item"
         routerLinkActive="active"
         [routerLink]="[item.router]"
       >
         {{ item.title }}
       </li>
     </ul>

Configurar para Angular17

Important

URL Para configurar alias de importaciones en Typescrips 👉 Ejemplo

  • En app.routes.ts

              export const routes: Routes = [
            {
              path: 'dashboard',
              loadComponent: () => import('./dashboard/dashboard.component'),
              children: [
                {
                  path: 'change-detection',
                  title: 'Change Detection',
                  loadComponent: () =>
                    import(
                      './dashboard/pages/change-detection/change-detection.component'
                    ),
                },
                {
                  path: 'control-flow',
                  title: 'Control Flow',
                  loadComponent: () =>
                    import('./dashboard/pages/control-flow/control-flow.component'),
                },
                {
                  path: 'defer-options',
                  title: 'Defer Options',
                  loadComponent: () =>
                    import('./dashboard/pages/defer-options/defer-options.component'),
                },
                {
                  path: 'defer-views',
                  title: 'Defer Views',
                  loadComponent: () =>
                    import('./dashboard/pages/defer-views/defer-views.component'),
                },
                {
                  path: 'user/:id',
                  title: 'User View',
                  loadComponent: () => import('./dashboard/pages/user/user.component'),
                },
                {
                  path: 'users-list',
                  title: 'Users List',
                  loadComponent: () => import('./dashboard/pages/users/users.component'),
                },
                {
                  path: 'view-transition',
                  title: 'View Transition',
                  loadComponent: () =>
                    import('./dashboard/pages/view-transition/view-transition.component'),
                },
                {
                  path: '',
                  redirectTo: 'control-flow',
                  pathMatch: 'full',
                },
              ],
            },
          
            {
              path: '**',
              redirectTo: '/dashboard',
              pathMatch: 'full',
            },
          ];
    • En cada componente ts se añade default desde el padre hasta los hijos
       //componente padre:
    
         import { Component } from '@angular/core';
         import { RouterModule } from '@angular/router';
         
         @Component({
           standalone: true,
           imports: [RouterModule],
           templateUrl: './dashboard.component.html',
           styles: ``
         })
         export default class DashboardComponent {
         
         }
     //componente hijo
     export default class ChangeDetectionComponent {
        
        }
  • En el ts donde se muestre el menu:

    import { Component } from '@angular/core';
    import { routes } from '../../app.routes';
    import { CommonModule } from '@angular/common';
    import { RouterModule } from '@angular/router';
    
    @Component({
     selector: 'sidemenu',
     standalone: true,
     imports: [CommonModule, RouterModule],
     templateUrl: './sidemenu.component.html',
     styleUrl: './sidemenu.component.scss',
    })
    export class SidemenuComponent {
     public menuItems = routes
       .map((route) => route.children ?? [])
       .flat()
       .filter((route) => route && route.path)
       .filter((route) => !route.path?.includes(':'));
        }}
    • Y en el html
       <div id="nav" class="w-full px-6">
         <!---------------- Dashboard MenuItem---------------------->
         @for (item of menuItems; track $index) {
     
           <a
           [routerLink]="item.path"
           routerLinkActive="bg-slate-400"
     
           href="#"
           class="w-full px-2 inline-flex space-x-2 items-center text-base font-regular px-4 py-4 boder-b py-3  text-white flex"
         >
           <div class="flex flex-col">
             <span class="text-lg ftext-slate-300 font-bold leading-5"
               >{{item.title}}</span
             >
             <span class="text-sm text-white/50 hidden md:block">{{item.path}}</span>
             </div>
           </a>
      }
      </div>

${\color{orange}Back\space}$ 🔙

  1. Guard

Crear guard

ng g guard nombreGuard2 --skip-tests

Crear guard con CanActivate

 ng g guard nombreGuard --implements=CanActivate --skip-tests

Crear guard con CanActivate y guard funcional

  ng g guard isAuthenticated --functional --implements=CanActivate --skip-tests

${\color{orange}Back\space}$ 🔙

  1. flat

ng g c mi-carpeta/componente-nombre --flat
  1. Pipes

    Crear pipes

  ng generate pipe nombre-pipe --skip-import
  1. Popup

    Generar popup

    npm i ng-angular-popup --force
    
    • En app.module.ts
    import { NgToastModule } from 'ng-angular-popup';
    
     imports: [
         NgToastModule
     ],

${\color{orange}Back\space}$ 🔙

  1. Confirm-box

    Generar confirm-box

    npm i ng-confirm-box --force
    
 ```
  * En app.module.ts
 ```TypeScript
 import { NgConfirmModule } from 'ng-confirm-box';

  imports: [
    NgConfirmModule
  ],
  ```

${\color{orange}Back\space}$ 🔙

  1. Directivas

### Directivas estructurales
  • *ngIf
    • \ngIfElse
  • *ngFor
  • *ngSwitch

Ejemplos estructurales

  • *ngIf (Condicional)
<div *ngIf="mostrarElemento">
  Este elemento se mostrará si la variable mostrarElemento es verdadera.
</div>
  • \ngIfElse
<div *ngIf="isUserLoggedIn; else elseBlock">
      <h2>Bienvenido, Usuario</h2>
    </div>

    <ng-template #elseBlock>
      <h2>Por favor, inicia sesión</h2>
    </ng-template>
 isUserLoggedIn = false;
  • *ngFor (Repetición)
<ul>
  <li *ngFor="let item of listaDeItems">
    {{ item }}
  </li>
</ul>
  • *ngSwitch (Conmutación)
<div [ngSwitch]="tipoDeContenido">
  <p *ngSwitchCase="'texto'">Este es un contenido de texto.</p>
  <div *ngSwitchCase="'imagen'">
    <img src="imagen.png" alt="Imagen">
  </div>
  <p *ngSwitchDefault>Contenido por defecto cuando no coincide ningún caso.</p>
</div>

${\color{orange}Back\space}$ 🔙

Directivas de atributo

  • [ngStyle] :Permite aplicar clases de manera condicional.
  • [ngClass] :Permite aplicar estilos de manera condicional.
  • [ngModel] :Utilizada para la vinculación bidireccional en formularios.

Ejemplos atributo

  • [ngStyle]
<!-- Aplica un estilo de fondo rojo si la variable fondoRojo es verdadera -->
<div [ngStyle]="{'background-color': fondoRojo ? 'red' : 'transparent'}">
 Este elemento tiene fondo rojo si fondoRojo es verdadera.
</div>
  • [ngClass]
<!-- Aplica la clase "resaltado" si la variable esVerde es verdadera -->
<div [ngClass]="{'resaltado': esVerde}">
 Este elemento tiene la clase "resaltado" si esVerde es verdadera.
</div>
  • [ngModel]
<!-- Utiliza ngModel para vincular el valor del input a la variable nombre -->
<input [(ngModel)]="nombre" placeholder="Ingrese su nombre">

<!-- Muestra el valor vinculado -->
<p>Tu nombre es: {{ nombre }}</p>

${\color{orange}Back\space}$ 🔙

Directivas de eventos

  • (click): Captura eventos de clic.
  • (input): Captura eventos de entrada en elementos de formulario.
  • (submit): Captura eventos de envío de formularios.
  • (mouseover): Captura eventos cuando el mouse pasa por encima del elemento.
  • (mouseout): Captura eventos cuando el mouse sale del elemento.
  • (keyup): Captura eventos de liberación de tecla.
  • (keydown): Captura eventos de presión de tecla.
  • (focus): Captura eventos cuando un elemento recibe el foco.
  • (blur): Captura eventos cuando un elemento pierde el foco.

Ejemplos eventos

  • (click)
   <!-- Ejecuta la función handleClick cuando se hace clic en el botón -->
<button (click)="handleClick()">Haz clic</button>
// En el componente TypeScript
handleChange(event: Event) {
  const inputElement = event.target as HTMLInputElement;
  console.log('Texto ingresado:', inputElement.value);
}
  • (input)
<!-- Ejecuta la función handleChange cuando se ingresa texto en el campo de entrada -->
<input (input)="handleChange($event)" placeholder="Ingresa texto">
// En el componente TypeScript
handleChange(event: Event) {
  const inputElement = event.target as HTMLInputElement;
  console.log('Texto ingresado:', inputElement.value);
}
  • (submit)
<!-- Ejecuta la función handleSubmit cuando se envía el formulario -->
<form (submit)="handleSubmit()">
  <!-- Otros campos del formulario -->
  <button type="submit">Enviar</button>
</form>
// En el componente TypeScript
handleSubmit() {
  console.log('Formulario enviado');
  // Puedes realizar acciones adicionales aquí, como enviar datos al servidor.
}
  • (mouseover)
<div (mouseover)="handleMouseOver()">Pasa el mouse aquí</div>
  • (mouseout)
<div (mouseout)="handleMouseOut()">Retira el mouse de aquí</div>
  • (keydown)
<input (keydown)="handleKeyDown($event)" placeholder="Presiona una tecla">
  • (focus)
<input (focus)="handleFocus()" placeholder="Enfócame">
  • (blur)
<input (blur)="handleBlur()" placeholder="Pierdo el foco">

${\color{orange}Back\space}$ 🔙

Directivas personalizadas

ng g d nombre-directiva --skip-import
import { Directive, ElementRef, HostListener, Input } from '@angular/core';

@Directive({
selector: '[appNombreDirectiva]'
})
export class NombreDirectivaDirective {

@Input() highlightColor: string = ''; // Color de resaltado por defecto

constructor(private el: ElementRef) {}

@HostListener('mouseenter') onMouseEnter() {
  this.highlight(this.highlightColor || 'yellow');
}

@HostListener('mouseleave') onMouseLeave() {
  this.highlight('');
}

private highlight(color: string) {
  this.el.nativeElement.style.backgroundColor = color;
}
}
<div appHighlight [highlightColor]="'cyan'">
Pasa el ratón sobre mí
</div>

Explicaciòn1.

${\color{orange}Back\space}$ 🔙

Event Binding

👀 URL Event binding

  1. Compilar

    dist/

    ng build 
    

    Producción

    ng build --configuration=production
    

${\color{orange}Back\space}$ 🔙

  1. Interceptor

Manejan y modifican solicitudes HTTP antes de que se envíen al servidor y las respuestas antes de que lleguen a la aplicación. Aquí hay un ejemplo sencillo de cómo podrías usar un interceptor.

  • Ejemplo
    • ${\color{blue}1º Generar\space interceptor}$

      ng g interceptor my-interceptor --skip-tests
      
    • ${\color{blue}2º Implementar\space lógica\space en\space el \space interceptor}$

      // my-interceptor.interceptor.ts
      
      import { Injectable } from '@angular/core';
      import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
      import { Observable } from 'rxjs';
      
      @Injectable()
      export class MyInterceptor implements HttpInterceptor {
        intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
          // Agregamos el encabezado personalizado a la solicitud
          const modifiedRequest = request.clone({
            setHeaders: {
              'X-My-Header': 'ValorPersonalizado'
            }
          });
      
          // Continuamos con la solicitud modificada
          return next.handle(modifiedRequest);
        }
      }
      
    • ${\color{blue}3º Implementar\space en\space el\space módulo \space donde\space se \space quiera\space usar\space o\space globalmente\space en\space el \space interceptor}$

      // app.module.ts
      
      import { BrowserModule } from '@angular/platform-browser';
      import { NgModule } from '@angular/core';
      import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
      import { MyInterceptor } from './path-to-my-interceptor/my-interceptor.interceptor';
      
      import { AppComponent } from './app.component';
      
      @NgModule({
        declarations: [AppComponent],
        imports: [BrowserModule, HttpClientModule],
        providers: [
          {
            provide: HTTP_INTERCEPTORS,
            useClass: MyInterceptor,
            multi: true
          }
        ],
        bootstrap: [AppComponent]
      })
      export class AppModule {}
      

${\color{orange}Back\space}$ 🔙

  1. Ciclos de vida

    ngOnChanges

    Se ejecuta cuando hay cambios en las propiedades de entrada del componente.

    ngOnInit

    Se ejecuta después de que Angular ha inicializado todas las propiedades del componente.

    ngDoCheck

    Se ejecuta durante cada detección de cambios y verificación de expresiones.

    ngAfterViewInit

    Se ejecuta después de que la vista del componente y sus vistas secundarias hayan sido inicializadas.

    ngOnDestroy

    Se ejecuta después de que la vista del componente y sus vistas secundarias hayan sido inicializadas.

    LifeCycle

    • Ciclo de Vida 👉 Repo

Ejemplos

import { Component, OnChanges, OnInit, DoCheck, AfterViewInit, OnDestroy } from '@angular/core';

@Component({
  selector: 'app-ciclos-de-vida',
  template: `
    <div>
      <h2>Ciclos de Vida del Componente</h2>
      <p>{{ message }}</p>
    </div>
  `
})
export class CiclosDeVidaComponent implements OnChanges, OnInit, DoCheck, AfterViewInit, OnDestroy {
  message: string = '';

  constructor() {
    console.log('Constructor');
    this.message += 'Constructor\n';
  }

  ngOnChanges() {
    console.log('ngOnChanges');
    this.message += 'ngOnChanges\n';
  }

  ngOnInit() {
    console.log('ngOnInit');
    this.message += 'ngOnInit\n';
  }

  ngDoCheck() {
    console.log('ngDoCheck');
    this.message += 'ngDoCheck\n';
  }

  ngAfterViewInit() {
    console.log('ngAfterViewInit');
    this.message += 'ngAfterViewInit\n';
  }

  ngOnDestroy() {
    console.log('ngOnDestroy');
    this.message += 'ngOnDestroy\n';
  }
}

${\color{orange}Back\space}$ 🔙

  1. Crear JSON Server

    • Installar de manera global
     npm i -g json-server
    
    • Crear db.json
     json-server --watch db.json
    
    • Levantar db.json
     json-server --watch db.json
    
  2. URL importantes

    Diseño

    Tutoriales

    APIs

    HostListener

    Librerias

    BD

    Instalables

    Subir Web

    NPMjs

    PDF Atajos

    PDF atajos: [FernendoH]angular-cheat-sheet.pdf

    Repositorios

    Tips Readme

Note

Esto es info adicional

Tip

Una sugerencia o consejo

Important

Información importante

Warning

Atencón del usuario

Caution

Consecuencias negativas si nos haces caso

${\color{orange}Back\space}$ 🔙

Footnotes

  1. @Directive({ selector: '[appHighlight]' }) define la directiva appHighlight y especifica que se puede aplicar a elementos con el atributo appHighlight. @Input() highlightColor: string = ''; define una propiedad de entrada (highlightColor) que permite al usuario especificar un color de resaltado cuando utiliza la directiva. @HostListener escucha eventos en el elemento que tiene la directiva. En este caso, escuchamos los eventos mouseenter y mouseleave y llamamos a las funciones correspondientes. private highlight(color: string) es una función privada que cambia el color de fondo del elemento en función del color proporcionado.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.