{"id":20094191,"url":"https://github.com/naopeke/angular_commands","last_synced_at":"2026-06-08T11:31:36.061Z","repository":{"id":212110490,"uuid":"730734239","full_name":"naopeke/Angular_Commands","owner":"naopeke","description":"About Angular","archived":false,"fork":false,"pushed_at":"2023-12-21T09:11:43.000Z","size":189,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-02T16:16:58.751Z","etag":null,"topics":["angular","reference-material"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/naopeke.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-12-12T14:59:23.000Z","updated_at":"2024-02-02T08:41:03.000Z","dependencies_parsed_at":"2024-11-13T16:49:49.339Z","dependency_job_id":"6649c50e-def2-43d3-b39d-7fc9af578e71","html_url":"https://github.com/naopeke/Angular_Commands","commit_stats":null,"previous_names":["naopeke/angular-concepto","naopeke/angular-commands"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/naopeke/Angular_Commands","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/naopeke%2FAngular_Commands","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/naopeke%2FAngular_Commands/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/naopeke%2FAngular_Commands/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/naopeke%2FAngular_Commands/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/naopeke","download_url":"https://codeload.github.com/naopeke/Angular_Commands/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/naopeke%2FAngular_Commands/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34061121,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-08T02:00:07.615Z","response_time":111,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["angular","reference-material"],"created_at":"2024-11-13T16:49:42.662Z","updated_at":"2026-06-08T11:31:36.042Z","avatar_url":"https://github.com/naopeke.png","language":null,"funding_links":[],"categories":[],"sub_categories":[],"readme":"# Angular Commands\n```\nnpm i -g @angular/cli@16.2.10\n```\n```\nnpm uninstall -g @angular/cli\n```\n```\nnpm cache clean --force\n```\n```\nng new my-app(nombre de aplicacion)\u003c/p\u003e\n```\n\n**MODULOS CON CLI**  \nモジュールの作成\n```\nng generate module nombre-del-modulo\nng g m nombre-del modulo\n```\n\n**MODULOS**\n```\nimport{ NgModule } from '@angular/core';\nimport { CommonModule } from '@angular/common'\nimport { MiComponente } from './mi-componente.component'\n\n@NgModule({\u003cbr\u003e\n    declarations: [MiComponente],\n    imports: [CommonModule],\n    exports: [MiComponente]\n})\n\nexport class MiModulo {}\n```\n\n**COMPONENTS CON CLI**  \nコンポーネントの作成\n```\nng generate component nombre-del componente\nng g c nombre-del componente\n```\n\n**4 archivos**\n__.component.ts\u003cbr\u003e\n__.component.html\u003cbr\u003e\n__.component.css\u003cbr\u003e\n__.component.spec.ts\u003cbr\u003e\n\n```\nnpm start\u003cbr\u003e\n```\n**Actively supported versions**\nhttps://angular.io/guide/versions\nNode.js\n```\nnvm install 18.10.0 // to install the version of node.js I wanted\nnvm use 18.10.0  // use the installed version\n```\nAngular (Downgrade @angular-devkit/build-angular)\n```\nnpm list @angular-devkit/build-angular\nnpm install @angular-devkit/build-angular@16.2.10 --save-dev\n```\n\nhttp://localhost:4200/\n\n**親のコンポーネント作成（myApp-src-app内トップ）**\n```\nng g c padre\n```\n```\napp.module.ts\n@NgModule({\n    declarations: [\n        AppComponent,\n        PadreComponent\n        // added automatically\n    ]\n})\n```\n\n**INPUT**  \n親コンポーネントから子コンポーネントに値を引き渡す   \nhttps://qiita.com/masaks/items/677195b78379e0877e24\n```\n//Componente hijo\n@Input() datoEntrada: string;\n\n//Componente padre\n\u003capp-hijo [datoEntrada]=\"valorDesdePadre\"\u003e\u003c/app-hijo\u003e\n\n//Componente padre\nvalorDesdePadre = \"Hola, mundo!\"\n\n//Componente hijo template\n{{ datoEntrada }}\n```\n\n**OUTPUT**  \n 子コンポーネントから親コンポーネントにイベント(値)を引き渡す\n```\n//Componente hijo\n@Output() messageEvent = new EventEmitter\u003cstring\u003e();\nmessage: string = '';\n\nsendMessage(){\n    this.messageEvent.emit(this.message)\n}\n\n//Componente hijo\n\u003cdiv\u003e\n\u003clabel for=\"childInput\"\u003eMensaje:\u003c/label\u003e\n\u003cinput id=\"childInput\"\u003e [(ngModel)]=\"message\" /\u003e\n\u003cbutton (click)=\"sendMessage()\"\u003eEnviar Mensaje\u003c/button\u003e\n\n//Componente padre\nreceivedMessage: string = '';\n\nreceiveMessage(message: string){\n    this.receivedMessage = message;\n}\n\n//Componente padre\n\u003cdiv\u003e\u003cbr\u003e\n\u003capp-child (messageEvent)=\"receiveMessage($event)\"\u003e\u003c/app-child\u003e\n\u003cp\u003eMensaje recibido en el padre {{ receivedMessage}}\u003c/p\u003e\n```\n\n**Servicio con Cli**  \nサービスとは、アプリケーションのロジックやデータを扱うためのクラスです。  \nAngularでは基本的に、コンポーネントが画面の表示を担当し、サービスがその他の処理を担当するように設計します。  \nhttps://tech.quartetcom.co.jp/2023/02/28/angular-service-providing-guide/\n```\nng generate service nombre-del-servicio\nng g s nombre-del-servicio\n```\n```\n@import { Injectable } from '@anglar/core';\n\n@Injectable({\n    providedIn: 'root'\n})\n\nexport class MiServicioService {\n    constructor() {}\n\n      //Métodos y lógica del servicio\n}\n```\n**Inyeccion de dependencias**   \n依存性の注入  Inject関数  \nhttps://zenn.dev/tkawa01/articles/d7245446018de0  \nhttps://zenn.dev/lacolaco/articles/why-inject-function-wins  \nhttps://angular.jp/guide/dependency-injection  \nhttps://angular.jp/guide/dependency-injection-in-action\n```\nimport { Component } from '@anglar/core';\nimport { MiServicio } from './mi-servicio.service';\n\n@Component({\n    selector: 'app-mi-componente',\n    templateUrl: './mi-componente.component.html'\n})\nexport class MiComponente {\n    constructor(privete miServicio: MiServicio){\n        //una variable, miServicio e inyecta esta forma de MiServicio\n        //...\n        //a partir de Angular17, \"inject\". servicio inject MiServicio\u003cbr\u003e\n    }\n}\n```\n\n**Directiva**  \nhttps://zenn.dev/knts0/articles/8afe1dd9d8981daf8286\nディレクティブ\n```\nng generate directive nombre-de-la-directiva\nng g d nombre-de-la-directiva\n```\n```\n//html\n\u003cdiv appMiDirectiva\u003e\n Este es un elemento con mi directiva personalizada.\n \u003c/div\u003e\n\n//nombre-de-la-directiva.directive.ts\nimport { Directive, ElementRef } from '@angular/core';\n\n@Directive({\n    selector: '[appMiDirectiva]'\n})\nexport class MiDirectivaDirective {\n    constructor(private el: ElementRef){\n        //Accede al elemento del DO en el que se aplica la directiva (this.el.nativeElement)\n        this.el.nativeElement.style.backgroundColor = 'yellow';\n    }\n}\n```\n\n**PIPES**\n```\nng generate pipe nombre-del-pipe\nng g p nombre-del-pipe\n```\n```\n//nombre-del-pipe.pipe.ts\nimport { Pipe, PipeTransform } from '@angular/core';\n\n@Pipe({\n    name: 'miPipe'\n})\nexport class MiPipe implements PipeTransform {\n    transform(valor: any): any{\n        //Implementa la lógica de transformación aquí\n        return valor.toUpperCase();\n    }\n}\n```\n```\n\u003cp\u003e{{texto | miPipe }}\u003c/p\u003e\nhttps://angular.io/guide/pipes\n```\n\n**Rutas(Routes)**\n```\n\u003cp\u003econst routes: Routes = [\n    { path: 'inicio', component: InicioComponent },\n    { path: 'productos', component: ProductosComponent },\n    { path: 'contacto', component: ContactoComponent },\n]\u003c/p\u003e\n```\n\n**Router Outlet**\n```\n\u003crouter-outlet\u003e\u003c/router-outlet\u003e\n```\n\n**Navegación**\n```\n\u003ca routerLink=\"/inicio\"\u003eInicio\u003c/a\u003e\n```\n\n**Parámetros de Ruta**\n```\n{ path: 'producto/:id', component: DetalleProductoComponent }\n\u003ca [routerLink]=\"['/producto', producto.id]\"\u003eVer Detalles\u003c/a\u003e\n```\n\n**routerLinkActive**\n```\n\u003cnav\u003e\n\u003ca routerLink=\"/inicio\" routerLinkActive=\"active\"\u003eInicio\u003c/a\u003e\n\u003ca routerLink=\"/productos\" routerLinkActive=\"active\"\u003eProductos\u003c/a\u003e\n\u003ca routerLink=\"/contacto\" routerLinkActive=\"active\"\u003eContacto\u003c/a\u003e\n\u003c/nav\u003e\n```\n\n**Parámetros por la URL**\n1. Definir una ruta con varios parámetros:\n```\nconst routes: Routes = [\n    { path: 'producto/:categoria/:id', component: DetalleProductoComponent },\n];\n```\n\n2. Enlazar a la ruta con múltiples parámetros:\n```\n\u003ca [routerLink]=\"['/producto', producto.categoria, producto.id]\"\u003eVer Detalles\u003c/a\u003e\n```\n\n3. Recuperar los parámetros en el componente:\n```\nimport { ActivatedRoute } from '@angular/router';\n\n//...\n\nconstructor(private route: ActivatedRoute) {}\n\nngOnInit(){\n    this.route.params.subscribe(params =\u003e {\n        const categoria = params['categoria'];\n        const productId = params['id'];\n        // Hacer algo con los valores de los parámetros\n    })\n}\n```\n\n**Navegar desde el controller**\n```\nimport { Router } from '@angular/router';\n\n//...\n\nconstructor(private router: Router) {}\n\n//...\n\nnavegarAProducto(productoId: number){\n    //Puedes navegar a una ruta especifica programáticamente\n    this.router.navigate(['/producto, productoId]);\n\n}\n```\n\n**Bootstrap**\n```\nng new landing-page-angular\n```\n```\nnpm i bootstrap@5.3.2\n```\n\nルーティングモジュール(app-routing.module.ts)を手動で追加:\n```\nng generate module app-routing --flat --module=app\n```\nあるいは  \n新しいプロジェクトを--routingフラグをつけて作成\n```\nng new my-app --routing\n```\n\nnode_module - dist - css - bootstrap.min.css - (click) copy relative path \n=\u003e (paste)angular.json \n```\n//27, 92\n\"styles\": [\n    \"src/styles.css\",\n    \"node_modules/bootstrap/dist/css/bootstrap.min.css\"\n]\n```\nnode_module - dist - js - bootstrap.bundle.min.js - (click) copy relative path\n```\n//30, 95\n    \"scripts\": [\n    \"node_modules/bootstrap/dist/js/bootstrap.bundle.min.js\"\n    ]\n```\n**Crear otros componentes**\n```\nng g c home\n```\n```\nng g c products\n```\n```\nng g c contact\n```\n```\nng g c product-detail\n```\n\n**Estructuras de Control**  \n**ngIf**\n```\n\u003cdiv *ngIf = \"mostrarElemento\"\u003e\n Contenido visible si mostrarElemento es true.\n\u003c/div\u003e\n```\n**ngFor**\n```\n\u003cul\u003e\n\u003cli *ngFor=\"let item of listaItems\"\u003e\n{{ item }}\n\u003c/li\u003e\n\u003c/ul\u003e\n```\n**ngSwitch**\n```\n\u003cdiv [ngSwitch]=\"opcion\"\u003e\n \u003cp *ngSwitchCase=\"'opcion1'\"\u003eContenido para opción 1\u003c/p\u003e\n \u003cp *ngSwitchCase=\"'opcion2'\"\u003eContenido para opción 2\u003c/p\u003e\n \u003cp *ngSwitchDefault\u003eContenido por defecto\u003c/p\u003e\n\u003c/div\u003e\n```\n**ngClass**\n```\n\u003cdiv [ngClass]=\"{'clase1': condicion1, 'clase2': condicion2}\"\u003e\n  //Contenido con clases dinámicos\n\u003c/div\u003e\n```\n**ngStyle**\n```\n\u003cdiv [ngStyle]=\"{'color': color, 'font-size': tamano}\"\u003e\n  //Contenido con estilos dinámicos\n\u003c/div\u003e\n```\n**ngContainer**\n```\n\u003cng-container *ngIf=\"condicion\"\u003e\n  //Contenido que no afecta al DOM directamente\n\u003c/ng-container\u003e\n```\n**otras estructuras de control:**  \nngTemplate  \nngPlural  \nngComponentOutlet  \n\n**Formulario**\nImportar FormsModule para formularios de plantilla\n```\nimport { FormsModule } from '@angular/forms';\n\n@NgModule({\n    declarations: [\n        //tus componentes aquí\n    ],\n    imports: [\n        FormsModule,\n        // otros modulos que estés utilizando\n    ],\n    bootstrap: [AppComponent],\n})\nexport class AppModule {}\n```\n**Formularios basados en plantillas (Template-driven);**\n```\n\u003cform #myForm=\"ngForm\" (ngSubmit)=\"onSubmit()\"\u003e\n\u003clabel for =\"name\"\u003eNombre:\u003c/label\u003e\n\u003cinput type=\"text\" id=\"name\" name=\"name\" [(ngModel)]=\"user.name\" required\u003e\n\n\u003clabel for =\"email\"\u003eCorreo:\u003c/label\u003e\n\u003cinput type=\"email\" id=\"email\" name=\"email\" [(ngModel)]=\"user.email\" required\u003e\n\n\u003cbutton type=\"submit\"\u003eEnviar\u003c/button\u003e\n\u003c/form\u003e\n```\n**Manejo de estado y errores**\n```\n\u003cdiv *ngIf=\"!name.valid \u0026\u0026 name.touched\"\u003eNombre es obligatorio.\u003c/div\u003e\n```\n**Importar ReactiveFormsModule para formularios reactivos**\n```\nimport { FormsModule } from '@angular/forms';\n\n@NgModule({\n    declarations: [\n        // tus componentes aquí\n    ],\n    imports: [\n        ReactiveFormsModule\n        // otros módulos que estés utilizando\n    ],\n    bootstrap: [AppComponent],\n})\nexport class AppModule {}\n```\n**Formularios reactivoe (Reactive): utiliza el servicio FormBuilder**\nHTML\n```\n\u003cform [formGroup]=\"myForm\" (ngSubmit)=\"onSubmit()\"\u003e\n\u003clabel for=\"name\"\u003eNombre:\u003c/label\u003e\n\u003cinput type=\"text\" id=\"name\" formControlName=\"name\"\u003e\n\n\u003clabel for=\"email\"\u003eCorreo:\u003c/label\u003e\n\u003cinput type=\"email\" id=\"email\" formControlName=\"email\"\u003e\n\n\u003cbutton type=\"submit\"\u003eEnviar\u003c/button\u003e\n```\nTS\n```\nimport { FormBuilder, FormGroup, Validators } from '@angular/forms';\n\nconstructor(private fb: FormBuilder){\n    this.myForm = this.fb.group( {\n        name: ['', Validators.required],\n        email: ['', [Validators.required, Validators.email]],\n    });\n}\n```\n**Manejo de estado y errores**\n```\n\u003cdiv *ngIf=\"myForm.get('name').hasError('required') \u0026\u0026 myForm.get('name').touched\"\u003e\n Nombre es obligatorio.\n\u003c/div\u003e\n\u003cdiv *ngIf=\"myForm.get('email').hasError('email') \u0026\u0026 myForm.get('email').touched\"\u003e\n Correo no válido.\n\u003c/div\u003e\n```\n**Ciculo de vida**  \n1.ngOnChanges  \n1.ngOnInit  \n1.ngDoCheck  \n1.ngAfterContentInit  \n1.ngAfterContentChecked  \n1.ngAfterViewInit  \n1.ngAfterViewChecked  \n1.ngOnDestroy  \n\n**ngOnChanges**\nnombreInputというプロパティがあり、親コンポーネントから変わった際に、ngOnChangesが動く。  \nngOnChangeの中からは、パラメータchangesからその変更にアクセスでき、その変更を実行できる。  \n```\nimport { Component, Input, OnChanges, SimpleChanges } from '@angular/core';\n\n@Component({\n    selector: 'app-mi-componente',\n    template: '\u003cp\u003eHola, {{ nombre }}\u003c/p\u003e\n})\nexport class MiComponente implements OnChanges {\n\n    //Propiedad de entrada\n    @Input() nombreInput:string;\n\n    //Propiedad del componente\n    nombre:string;\n\n    //Método ngOnChanges se llama cuando hay cambios en las propiedades de entrada\n    ngOnChanges(changes: SimpleChanges):void{\n        //Verifica si la propiedad de entrada 'nombreInput' ha cambiado\n        if(changes.nombreInput){\n            this.nombre = changes.nombreInput.currentValue;\n            console.log(`Se ha cambiado el valor de nombreInput a: ${this.nombre}`);\n        }\n    }\n}\n\n```\n**ngOnInit**\nngOnInitはすべてのコンポーネントのプロパティを開始したあとに実行する。\n```\nimport { Component, OnInit } from '@angular/core';\n\n@Component({\n    selector: 'app-mi-componente',\n    template: '\u003cp\u003eHola, mundo!\u003c/p\u003e',\n})\nexport class MiComponente implements OnInit {\n\n    //Propiedad de ejemplo\n    nombre: string;\n\n    //Constructor del componente\n    constructor(){\n        //Puedes incializar propiedades aquí, pero es una buena práctica hacerlo en ngOnInit\n    }\n\n    //Método ngOnInit se llama después de que Angular ha inicializado todas las propiedades del componente\n    ngOnInit(): void {\n        this.nombre = 'Usuario';\n        console.log(`Hola, ${this.nombre}! El componente se ha inicializado`);\n    }\n}\n```\n**ngDoCheck**\nAngular内での変更を見つける。その度に発動するので複雑なものは入れないこと。\n```\nimport { Component, DoCheck } from '@angular/core';\n\n@Component({\n    selector: 'app-mi-componente',\n    template: '\u003cp\u003eHola, {{ nombre }}!\u003c/p\u003e',\n})\nexport class MiComponente implements DoCheck {\n}\n    nombre:string = 'Usuario';\n\n    //Método ngDoCheck se llama durante cada detección de cambios\n    ngDoCheck():void {\n        console.log('Se está ejecutando ngDoCheck');\n        //Puedes realizar acciones de verificación personalizadas aquí\n    }\n```\n**ngAfterContentInit**\n```\nimport { Component, AfterContentInit, ContentChild, ElementRef } from '@angular/core';\n\n@Component({\n    selector: 'app-mi-componente',\n    template: '\u003cng-content\u003e\u003c/ng-content\u003e',\n})\nexport class MiComponente implements AfterContentInit {\n\n    //ContentChild para acceder a un elemento dentro del contenido proyectado\n    @ContentChild('nombreElemento') nombreElemento: ElementRef;\n\n    //Método ngAfterContentInit se llama después de que Angular haya proyectado el contenido\n    ngAfterContentInit():void{\n        //Realizar acciones después de que el contenido haya sido inicializado\n        if(this.nombreElemento){\n            console.log(`Se ha encontrado un elemento con el nombre 'nombreElemento'.`);\n        }\n    }\n}\n```\n**ngAfterContentChecked**\n```\nimport { Component, AfterContentChecked, ContentChild, ElementRef } from '@angular/core';\n\n@Component({\n    selector: 'app-mi-componente',\n    template: '\u003cng-content\u003e\u003c/ng-content\u003e',\n})\nexport class MiComponente implements AfterContentChecked {\n\n    //ContentChild para acceder a un elemento dentro del contenido proyectado\n    @ContentChild('nombreElemento') nombreElemento: ElementRef;\n\n    //Método ngAfterContentChecked se llama después de cada verificación del contenido proyectado\n    ngAfterContentChecked():void {\n        //Realizar acciones después de cada verificación del contenido\n        if (this.nombreElemento){\n            console.log(`Se ha verificado el contenido y se ha encontrado un elemento con el nombre 'nombreElemento'.`);\n        }\n    }\n```\n**ngAfterViewInit**\n```\nimport { Component, AfterViewInit, ViewChild, ElementRef } from '@angular/core';\n\n@Component({\n    selector: 'app-mi-componente',\n    template: '\u003cp #miParrafo\u003eHola, mundo!\u003c/p\u003e,\n})\nexport class MiComponente implements AfterViewInit {\n\n    //ViewChild para acceder a un elemento en la vista del componente\n    @ViewChild('miParrafo') miParrafo: ElementRef;\n\n    //Método ngAfterViewInit se llama después de que Angular haya inicializado las vistas del componente\n    ngAfterViewInit():void {\n        //Realizar acciones después de que la vista haya sido inicializada\n        if (this.miParrafo){\n            console.log(`Se ha inicializado la vista y se ha encontrado un párrafo: ${this.miParrafo.nativeElement.textContent}`);\n        }\n    }\n}\n```\n**ngAfterViewChecked**\n```\nimport { Component, AfterViewChecked, ViewChild, ElementRef } from '@angular/core';\n\n@Component({\n    selector: 'app-mi-componente',\n    template: '\u003cp #miParrafo\u003e{{ mensaje }}\u003c/p\u003e,\n})\nexport class MiComponente implements AfterViewChecked {\n\n    mensaje: string = 'Hola, mundo!';\n\n    //ViewChild para acceder a un elemento en la vista del componente\n    @ViewChild('miParrafo') miParrafo: ElementRef;\n\n    //Método ngAfterViewChecked se llama después de cada verificación de las vistas del componente\n    ngAfterViewChecked():void {\n        //Realizar acciones después de cada verificación de las vistas\n        if(this.miParrafo){\n            console.log(`Se ha verificado la vista y el contenido del párrafo es: ${this.miParrafo.nativeElement.textContent}`);\n        }\n    }\n\n}\n```\n**ngOnDestroy**\n```\nimport { Component, OnDestroy } from '@angular/core';\nimport { Subscription } from 'rxjs';\n\n@Component({\n    selector: 'app-mi-componente',\n    template: '\u003cp\u003eAdiós, mundo!\u003c/p\u003e,\n})\nexport class MiComponente implements OnDestroy {\n\n    //Ejemplo de suscripción a un observable\n    private subscription: Subscription;\n\n    constructor(){\n        //Simulación de suscripción a un observable\n        this.subscription = new Subscription();\n    }\n\n    //Método ngOnDestroy se llama justo antes de que Angular destruya el componente\n    ngOnDestroy():void{\n        //Realizar limpieza, como desuscribirse de observables o liberar recursos\n        if (this.subscription){\n            this.subscription.unsubscribe();\n            console.log('Se ha desuscrito de la suscripción en ngOnDestroy');\n        }\n    }\n}\n```\n# API\nAPI  : Application Programing Interface   \nRest : REpresentational State Transfer  \nREST API は、REST アーキテクチャの制約に従って、RESTful Web サービスとの対話を可能にする アプリケーション・プログラミング・インタフェース (API または Web API) です。REST (Representational State Transfer) は、コンピュータ・サイエンティストの Roy Fielding によって作成された API の構築方法を定義する仕様であり、REST 用に設計された REST API (または RESTful API) は軽量で高速であるため、IoT (モノのインターネット)、モバイル・アプリケーション開発、サーバーレス・コンピューティングなどの先進的なコンテキストに最適です。  \nhttps://www.redhat.com/ja/topics/api/what-is-a-rest-api  \nHttpClientModuleをインポート  \n(NgModule APIとは）https://angular.jp/guide/ngmodule-api\n```\nimport { HttpClientModule } from '@angular/common/http';\n\n@NgModule({\n    declarations: [\n    //tus componentes aquí\n],\n    imports:[\n     HttpClientModule,\n    //otros módulos aquí\n],\nbootstrap: [AppComponent]\n})\nexport class AppModule { }\n```\n**使い方**\n```\nng generate service my-api\n```\n```\nimport { Injectable } from '@angular/core';\nimport { HttpClient } from '@angular/common/http';\nimport { Observable } from 'rxjs';\n\n@Injectable({\n providedIn: 'root'\n})\nexport class MyApiService {\n private apiUrl = 'https://mi-api.com';\n\nconstructor(private http: HttpClient) { }\n\ngetData(): Observable \u003cany\u003e {\n return this.http.get(`${this.apiUrl}/datos`);\n}\n\npostData(data:any): Observable\u003cany\u003e {\n return this.http.post(`${this.apiUrl}/enviar-datos`, data);\n}\n}\n```\n```\nimport { Component, OnInit } from '@angular/core';\nimport { MyApiService } from 'ruta-al-servicio';\n\n@Component({\n selector: 'app-mi-componente',\n templateUrl: './mi-componente.component.html',\n styleUrls:['./mi-componente.component.css']\n})\nexport class MiComponenteComponent implements OnInit {\nconstructor(private myApiService: MyApiService) { }\n\nngOnInit(): void{\nthis.myApiService.getData().subscribe({\n next: (data:any) =\u003e {\n//Manejar la respuesta de la API exitosa (next)\nconsole.log(data);\n},\nerror: (error:any) =\u003e {\n//Manejar errores\nconsole.error('Error en la solicitud HTTP:', error);\n}\n});\n}\n} \n```\n**api fake products**  \nFake Api  \n[https://github.com/keikaavousi/fake-store-api ](https://fakestoreapi.com/)  \nquicktype Convert JSON  \nhttps://quicktype.io/  \n\n**Property Binding**  \nAttributes - HTML =\u003e Attribute values cannot change  変化しない  \nProperties - DOM (Document Object Model) =\u003e Property values can change  変化する　　\nhttps://www.youtube.com/watch?v=N8FBmB2jme8  \n```\n\u003ch2\u003e Welcome {{ name }}}\u003c/h2\u003e\n\u003cinput [id]=\"myId\" type=\"text\" value=\"Vishwas\"\u003e\n\u003cinput id=\"{{ myId }}\" type=\"text\" value=\"Vishwas\"\u003e\n// properties: myId\n//Interpolation（補間：変数や式を埋め込んで、文字列やコードの一部を生成するプロセス）には、Stringでしか使えないという制限がある。\n//HTMLプロパティのBooleanをバインドするときはInterpolationが使えない。\n\u003cinput disabled=\"false\" id=\"{{ myId }}\" type=\"text\" value=\"Vishwas\"\u003e\n\u003cinput disabled={{ false }} id=\"{{ myId }}\" type=\"text\" value=\"Vishwas\"\u003e\n//この両方の場合、disabledが機能し、falseに意味はない。こういった場合に、プロパティバインディングを使う。  \n\u003cinput [disabled]=\"false\" id=\"{{ myId }}\" type=\"text\" value=\"Vishwas\"\u003e\n\nexport class TestComponent implements OnInit {\n public name = \"Codevolution\";\n public myId = \"testId\";\n constructor(){}\n\nngOnInit(){}\n}\n```\n他の方法はクラスを作成する\n```\n\u003cinput [disabled]=\"isDisabled\" id=\"{{ myId }}\" type=\"text\" value=\"Vishwas\"\u003e\n\u003cinput bind-disabled=\"isDisabled\" id=\"{{ myId }}\" type=\"text\" value=\"Vishwas\"\u003e\n\nexport class TestComponent implements OnInit {\n public name = \"Codevolution\";\n public myId = \"testId\";\n public isDisabled = true;\n```\n\n**Class Binding**  \nhttps://www.youtube.com/watch?v=Y6OP-lPJxgs  \ntest.component.ts  \n```\n\u003ch2 class=\"text-success\"\u003eCodevolution\u003c/h2\u003e\n\u003ch2 [class]=\"sucessClass\"\u003eCodevolution\u003c/h2\u003e\n\n\u003ch2 class=\"text-special\" [class]=\"successClass\"\u003eCodevolution\u003c/h2\u003e\n// Not italic style. Regular class attribute becomes a dummy attribute\n\u003ch2 [class.text-danger]=\"hasError\"\u003eCodevolution\u003c/h2\u003e\n//text-danger will be applied\n\n//To apply multiple classes, [ngClass]\n\u003ch2 [ngClass]=\"messageClasses\"\u003eCodevolution\u003c/h2\u003e\n// public hasError = false, public isSpecial = true; =\u003e green and italic\n// public hasError = true, public isSpecial = true; =\u003e red and italic\n\n\n\nstyles: [\n.text-success{\ncolor:green;\n}\n\n.text-danger{\ncolor:red;\n}\n\n.text-special {\nfont-style:italic;\n}\n]\nexport class TestComponent implements OnInit {\n public name = \"Codevolution\";\n public successClass = \"text-success\";\n public hasError = true;\n public isSpecial = true;\n public messageClasses = {\n    \"text-success\": !this.hasError,\n    \"text-danger\": this.hasError,\n    \"text-special\": this.isSpecial\n}\n\n\n constructor(){ }\n\n ngOnInit(){\n }\n}\n```\n**Style Binding**  \nhttps://www.youtube.com/watch?v=q256X6-u9Q8  \n```\n@Component({\n selector: 'app-test',\n template: `\n\u003ch2\u003e Welcome {{ name }} \u003c/h2\u003e\n\u003ch2 [style.color]=\"'orange'\"\u003e Style Binding\u003c/h2\u003e\n\u003ch2 [style.color]=\"hasError ? 'red' : 'green'\"\u003e Style Binding\u003c/h2\u003e\n//hasError is true, red. if not, green.\n\u003ch2 [style.color]=\"hightlightColor\"\u003e Style Binding\u003c/h2\u003e\n//hightlightColor: orange\n\u003ch2 [ngStyle]=\"titleStyles\"\u003eStyle Binding\u003c/h2\u003e\n//blue\n`,\nstyles: []\n})\nexport class TestComponent implements OnInit {\n\n    public name = \"Codevolution\";\n    public hasError = false;\n    public isSpecial = true;\n    public hightlightColor = \"orange\";\n    public titleStyles = {\n        color:\"blue\",\n        fontStyle:\"italic\"\n}\n```\n\n**Event Binding**  \nhttps://www.youtube.com/watch?v=ZfIc1_oj7uM  \n```\n@Component({\n selector: 'app-test',\n template: `\n    \u003ch2\u003eWelcome {{ name }}\u003c/h2\u003e\n    \u003cbutton (click)=\"onClick( $event )\"\u003eGreet\u003c/button\u003e\n    //\"Welcome to Codevolution\" and MouseEvent in console\n\n    \u003cbutton (click)=\"greeting='Welcome Vishwas'\"\u003eGreet\u003c/button\u003e\n    //\"Welcome Vishwas\" and no console\n\n    {{ greeting }}\n`,\nstyles: []\n})\nexport class TestComponent implements OnInit {\n\n    public name = \"Codevolution\";\n    public greeting=\"\";\n\n    constructor(){ }\n\n    ngOnInit(){\n}\n\n    onClick(event){\n    console.log('Welcome to Codevolution');\n    this.greeting = 'Welcome to Codevolution'\n    this.greeting = event.type;\n    //\"click\" and MouseEvent in console\n\n```\n**Template Reference Variables**\nhttps://www.youtube.com/watch?v=Oo0-r_YhoJs  \n```\n@Component({\n selector: 'app-test',\n template: `\n    \u003ch2\u003eWelcome {{ name }}\u003c/h2\u003e\n    \u003cinput #myInput type=\"text\"\u003e\n    \u003cbutton (click) =\"logMessage(myInput.value)\"\u003eLog\u003c/button\u003e\n    //What you typed (\"Vishwas\") in the console\n\n    \u003cbutton (click) =\"logMessage(myInput)\"\u003eLog\u003c/button\u003e\n    //\u003cinput type=\"text\"\u003e in the console\n`,\nstyles: []\n})\nexport class TestComponent implements OnInit {\n\n    public name = \"Codevolution\";\n\n    constructor(){ }\n\n    ngOnInit(){\n}\n\n    logMessage(value){\n    console.log(value);\n}\n\n```\n\n**Two way binding**  \nhttps://www.youtube.com/watch?v=DOWwWsbG1Sw  \n```\n@Component({\n selector: 'app-test',\n template: `\n    \u003cinput [(ngModel)]=\"name\" type=\"text\"\u003e\n    {{ name }}\n`,\n styles: []\n})\nexport class TestComponent implements OnInit {\n    public name=\"\";\n\n    constructor(){ }\n    ngOnInit(){\n    }\n\n}\n```\n\n**ngModel**  \nAngularで input 要素の value 属性を設定する場合、通常は ngModel ディレクティブを使います。  \n1. Angularフォームモジュールを利用するために FormsModule をインポート  \n```\n// app.module.ts\nimport { NgModule } from '@angular/core';\nimport { BrowserModule } from '@angular/platform-browser';\nimport { FormsModule } from '@angular/forms';\n\nimport { AppComponent } from './app.component';\n\n@NgModule({\n  declarations: [\n    AppComponent,\n  ],\n  imports: [\n    BrowserModule,\n    FormsModule, // FormsModuleをインポート\n  ],\n  bootstrap: [AppComponent]\n})\nexport class AppModule { }\n```\n2. コンポーネントのテンプレートで ngModel ディレクティブを使って input 要素の value をバインド  \n```\n// app.component.ts\nimport { Component } from '@angular/core';\n\n@Component({\n  selector: 'app-root',\n  template: `\n    \u003cinput type=\"text\" [(ngModel)]=\"value\"\u003e\n    \u003cp\u003eValue: {{ value }}\u003c/p\u003e\n  `,\n})\nexport class AppComponent {\n  value: string = \"initial value\";\n}\n\n```\nAngular 12以降では、FormsModule が ReactiveFormsModule に統合  \n\n**ngIf**  \nhttps://www.youtube.com/watch?v=nWst87nQmZQ\n```\n// test.component.ts\nimport { Component, OnInit } from '@angular/core';\n\n@Component({\n    selector: 'app-test',\n    template:`\n     \u003ch2 *ngIf=\"true\"\u003e\n        Codevolution\n    \u003c/h2\u003e\n    // \"Codevolution\" appears in the console\n\n    \u003ch2 *ngIf=\"false\"\u003e\n        Codevolution\n    \u003c/h2\u003e\n    //\"Codevolution\" doesn't appear in the console\n    \u003ch2 *ngIf=\"displayName\"\u003e\n        Codevolution\n    \u003c/h2\u003e\n    //displayName = true;\n    //\"Codevolution\" appears in the console\n    //displayName = false;\n    //\"Codevolution\" doesn't appear in the console\n\n    \u003ch2 *ngIf=\"displayName; else elseBlock\"\u003eCodevolution\u003c/h2\u003e\n\n    \u003cng-template #elseBlock\u003e\n    \u003ch2\u003e\n        Name is hidden\n    \u003c/h2\u003e\n    \u003c/ng-template\u003e\n    //else block is a reference to this block of HTML\n    //ng template tag is like a container for other elements that the ng-if directive can use to properly add or remove blocks of HTML from the DOM\n    //    displayName = false;\n    //  shows elseBlock \"Name is hidden\" appears in html\n\n    \u003cdiv *ngIf=\"displayName; then thenBlock; else elseBlock\"\u003e\u003c/div\u003e\n    \u003cng-template #thenBlock\u003e\n        \u003ch2\u003eCodevolution\u003c/h2\u003e\n    \u003c/ng-template\u003e\n\n    \u003cng-template #elseBlock\u003e\n        \u003ch2\u003eHidden\u003c/h2\u003e\n    \u003c/ng-template\u003e\n    // displayName = false;\n    // shows elseBlock \"Hidden\"\n    // displayName = true;\n    // shows thenBlock \"Codevolution\"\n `,\n})\nexport class TestComponent implements OnInit {\n\n    displayName = true;\n\n    constructor(){ }\n\n    ngOnInit(){\n    }\n}\n```\n**ngSwitch**  \nhttps://www.youtube.com/watch?v=WiDn2y1Ktws\n```\nimport { Component, OnInit } from '@angular/core';\n\n@Component({\n    selector: 'app-test',\n    template:`\n        \u003cdiv [ngSwitch]=\"color\"\u003e\n            \u003cdiv *ngSwitchCase=\"'red'\"\u003eYou picked red color\u003c/div\u003e\n            \u003cdiv *ngSwitchCase=\"'blue'\"\u003eYou picked blue color\u003c/div\u003e\n            \u003cdiv *ngSwitchCase=\"'green'\"\u003eYou picked green color\u003c/div\u003e\n            \u003cdiv *ngSwitchDefault\u003ePick again\u003c/div\u003e\n        \u003c/div\u003e\n        \n `,\n})\nexport class TestComponent implements OnInit {\n\n    puclic color = \"red\";\n\n    constructor(){ }\n\n    ngOnInit(){\n    }\n}\n```\n**ngFor**  \nhttps://www.youtube.com/watch?v=Du3p6QYGs3A  \n```\nimport { Component, OnInit } from '@angular/core';\n\n@Component({\n    selector: 'app-test',\n    template:`\n        \u003cdiv *ngFor=\"let color of colors\"\u003e\n            \u003ch2\u003e{{ color }}\u003c/h2\u003e\n        // red blue green yellow \n        \u003c/div\u003e\n\n        \u003cdiv *ngFor=\"let color of colors; index as i\"\u003e\n            \u003ch2\u003e{{i}} {{ color }}\u003c/h2\u003e\n        // 0 red 1 blue 2 green 3 yellow\n        \u003c/div\u003e\n\n        \n        \u003cdiv *ngFor=\"let color of colors; first as f\"\u003e\n            \u003ch2\u003e{{f}} {{ color }}\u003c/h2\u003e\n        // true red false blue false green false yellow\n        \u003c/div\u003e\n\n        \u003cdiv *ngFor=\"let color of colors; last as l\"\u003e\n            \u003ch2\u003e{{l}} {{ color }}\u003c/h2\u003e\n        // false red false blue false green true yellow\n        \u003c/div\u003e\n\n        \u003cdiv *ngFor=\"let color of colors; odd as o\"\u003e\n            \u003ch2\u003e{{o}} {{ color }}\u003c/h2\u003e\n        // false red true blue false green true yellow (Odd numbe)\n        \u003c/div\u003e\n\n        \n        \u003cdiv *ngFor=\"let color of colors; even as e\"\u003e\n            \u003ch2\u003e{{e}} {{ color }}\u003c/h2\u003e\n        // true red false blue true green false yellow (Odd numbe)\n        \u003c/div\u003e\n `,\n})\nexport class TestComponent implements OnInit {\n\n    puclic color = [\"red\", \"blue\", \"green\", \"yellow\"];\n\n    constructor(){ }\n\n    ngOnInit(){\n    }\n}\n```\n**Component Interaction @Input**  \napp.component.ts\n```\nimport { Component, OnInit } from '@angular/core';\n\n@Component({\n    selector: 'app-root',\n    templateUrl: '-/app.component.html',\n    styleUrls: ['./app.component.css]\n})\nexport class AppComponent {\n    title = 'app';\n    public name = \"Vishwas\";\n}\n```\napp.component.html  [PARENT]\n```\n\u003cdiv style=\"text-align:center\"\u003e\n  \u003ch1\u003e\n    Welcome to {{title}}\n  \u003c/h1\u003e\n\u003c/div\u003e\n\u003capp-test [parentData]=\"name\"\u003e\u003c/app-test\u003e\n```\ntest.component.ts  [CHILD}\n```\nimport { Component, OnInit, Input } from '@angular/core';\n\n@Component({\n    selector: 'app-root',\n    template:`\n\n        \u003ch2\u003e{{\"Hello \" + parentData}}\u003c/h2\u003e\n        // \"Hello Vishwas\" in the browser\n`,\n    styles: []\n})\nexport class TestComponent implements OnInit {\n\n    @Input() public parentData;\n\n    \n    @Input('parentData') public name;\n    //When you want to use the different property name than the one parent component uses, you can specify an alias\n    //I call this property as \"name\" within this componen, but input is still the parent data.\n    //In this case, \u003ch2\u003e{{\"Hello \" + name}}\u003c/h2\u003e\n\n    constructor(){ }\n\n    ngOnInit(){ }\n}\n```\n1.子コンポーネントに @Input プロパティを定義  \n![Captura desde 2023-12-21 10-01-39](https://github.com/naopeke/Angular_Commands/assets/143800388/04df3da9-c5e2-487f-b77c-7a89d7b0dcd7)\n  \n2.親コンポーネントから子コンポーネントにデータを渡す  \n![Captura desde 2023-12-21 10-01-56](https://github.com/naopeke/Angular_Commands/assets/143800388/22c7b30f-4e72-46fb-9de6-3c301c021c1c)\n\n\n **Component Interaction @Output**  \nThe way that a child component sends data to the parent component is using events.  \nSend \"hello codevolution\" from the text component to the app component, and display in the app component.  \n app.component.html [PARENT]\n```\n\u003cdiv style=\"text-align:center\"\u003e\n    \u003ch1\u003e\n        {{ message }}\n    \u003c/h1\u003e\n\u003c/div\u003e\n\u003capp-test (childEvent)=\"message=$event\" [parentData]=\"name\"\u003e\u003c/app-test\u003e\n//this $ event variable is going to refer to \"hey codevolution\"\n```\ntest.component.ts  [CHILD}\n```\nimport { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';\n\n@Component({\n    selector: 'app-test',\n    template:`\n\n        \u003ch2\u003e{{\"Hello \" + parentData}}\u003c/h2\u003e\n        \u003cbutton (click)=\"fireEvent()\"\u003eSend Event\u003c/button\u003e\n`,\n    styles: []\n})\nexport class TestComponent implements OnInit {\n\n    @Input('parentData') public name;\n\n    @Output public childEvent = new EventEmitter();\n\n    constructor(){ }\n\n    ngOnInit(){ }\n}\n\n    fireEvent(){\n        this.childEvent.emit('Hey Codevolution');\n}\n}\n```\napp.component.ts\n```\nimport { Component, OnInit } from '@angular/core';\n\n@Component({\n    selector: 'app-root',\n    templateUrl: '-/app.component.html',\n    styleUrls: ['./app.component.css]\n})\nexport class AppComponent {\n    title = 'app';\n    public name = \"Vishwas\";\n    pulic message =\"\";\n}\n```\n*On the latest Angular 6 version, in order to work, you will have to comment out the default import { EventEmitter } from 'events' and include  EventEmitter from '@angular/core'  \n\n1.子コンポーネントに @Output プロパティを定義  \n![Captura desde 2023-12-21 10-08-34](https://github.com/naopeke/Angular_Commands/assets/143800388/d853f75c-680a-4051-99b7-0bd987629e55)  \n  \n2.親コンポーネントでイベントを受け取る  \n![Captura desde 2023-12-21 10-08-52](https://github.com/naopeke/Angular_Commands/assets/143800388/98417bbd-e522-4307-992a-222e4c3259bb)\n\n\n\n**Pipes**  \ntest.component.ts\n```\nimport { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';\n\n@Component({\n    selector: 'app-test',\n    template:`\n\n        \u003ch2\u003e{{ name }}\u003c/h2\u003e\n        \u003ch2\u003e{{ name | lowercase }}\u003c/h2\u003e\n        // codevolution\n        \u003ch2\u003e{{ name | uppercase }}\u003c/h2\u003e\n        // CODEVOLUTION\n        \u003ch2\u003e{{ message | titlecase }}\u003c/h2\u003e\n        // Welcome To Codevolution\n\n        \u003ch2\u003e{{ name | slice:3 }}\u003c/h2\u003e\n        // evolution (from index 3)\n        \u003ch2\u003e{{ name | slice:3:5}}\u003c/h2\u003e\n        // ev (index from 3 and 4, 5 is excluded)\n        \u003ch2\u003e{{ person | json }}\u003c/h2\u003e\n        // {\"firstName\":\"John\", \"lastName\":\"Doe\"}\n\n        \u003ch2\u003e{{5.678 | number:'1.2-3'}}\u003c/h2\u003e\n        // 5.678\n        \u003ch2\u003e{{5.678 | number:'3.4-5'}}\u003c/h2\u003e\n        // 005.6780\n        \u003ch2\u003e{{5.678 | number:'3.1-2'}}\u003c/h2\u003e\n        // 005.68\n\n        \u003ch2\u003e{{ 0.25 | percent }}\u003c/h2\u003e\n        // 25%\n\n        \u003ch2\u003e{{ 0.25 | currency }}\u003c/h2\u003e\n        // $0.25\n        \u003ch2\u003e{{ 0.25 | currency: 'GBP' }}\u003c/h2\u003e\n        // £0.25\n        //ISO currency code: https://www.iso.org/iso-4217-currency-codes.html\n        \u003ch2\u003e{{ 0.25 | currency: 'GBP': 'code'}}\u003c/h2\u003e\n        // GBP0.25\n\n        \u003ch2\u003e{{ date }}\u003c/h2\u003e\n        // Sun Dec 03 2017 21:48:52 GMT+0530 (India Standard Time)\n        \u003ch2\u003e{{ date | date:'short' }}\u003c/h2\u003e\n        //12/3/17, 9:49PM\n        \u003ch2\u003e{{ date | date:'shortDate' }}\u003c/h2\u003e\n        //12/3/17\n        \u003ch2\u003e{{ date | date:'shortTime' }}\u003c/h2\u003e\n        //9:50PM\n`,\n    styles: []\n})\nexport class TestComponent implements OnInit {\n\n    public name = \"Codevolution\";\n    public message = \"Welcome to codevolution\";\n    public person = {\n        \"firstName\": \"John\",\n        \"lastName\": \"Doe\"\n}\n\n    public date = new Date();\n\n    constructor(){ }\n\n    ngOnInit(){ }\n}\n\n}\n```\n\n**service**  \nhttps://www.youtube.com/watch?v=y8lwG8IM82k  \nDo Not Repeat Yourself (DRY)  \nSingle Responsibility Principle  \n=\u003e Service :  -.service.ts\nA class with a specific purpose  \n1. Share data\n2. Implement application logic\n3. External Interaction\n\nDependency Injection\n1. Code without DI -drawbacks  \n2. DI as a design pattern\n3. DI as a framework\nhttps://www.youtube.com/watch?v=OFPIGlxunL0\n\napp.component.ts\n```\nimport { Component } from '@angular/core';\n\n@Component({\n selector:'app-root',\n templateUrl:'./app.component.html',\n styleUrls:['./app.component.css']\n})\nexport class AppComponent {\ntitle='Codevolution0;\n}\n```\nemployee-list.component.ts\n```\nimport { Component, OnInit } from '@angular/core';\n\n@Component({\n selector: 'employee-list',\n template: `\n \u003ch2\u003eEmployee List\u003c/h2\u003e\n \u003cul *ngFor=\"let employee of employees\"\u003e\n    \u003cli\u003e{{ employee.name }}\u003c/li\u003e\n\u003c/ul\u003e\n`,\n styles:[]\n})\nexport class EmployeeListComponent implements OnInit {\n\n    public employees = [\n        {\"id\":1, \"name\": \"Andrew\", \"age\": 30},\n        {\"id\":2, \"name\": \"Brandon\", \"age\":25},\n        {\"id\":3, \"name\": \"Christina\", \"age\":26},\n        {\"id\":4, \"name\": \"Elena\", \"age\":28}\n];\n```\nemployee-detail.component.ts\n```\nimport { Component, OnInit } from '@angular/core';\n\n@Component({\n selector: 'employee-detail',\n template: `\n \u003ch2\u003eEmployee Detail\u003c/h2\u003e\n \u003cul *ngFor=\"let employee of employees\"\u003e\n    \u003cli\u003e{{employee.id}}. {{ employee.name }} - {{employee.age}}\u003c/li\u003e\n\u003c/ul\u003e\n`,\n styles:[]\n})\nexport class EmployeeListComponent implements OnInit {\n\n    constructor(){}\n\n    ngOnInit(){}\n\n```\nCode without DI\n```\nclass Engine{\n constructor(){}\n}\nclass Tires{\n constructor(){}\n}\n```\n```\nclass Car{\n    engine;\n    tires;\n    constructor(){\n        this.engine = new Engine();\n        //class Engineのconstructor(parameter):petrol or diesel, にすると、new Engineがエラーになる\n        this.tires = new Tires();\n}\n```\nDI as a design pattern  \nDI is a coding pattern in which a class receives its dependencies from external sources rather than creating them itself.  \nwithout DI\n```\nclass Car{\n    engine;\n    tires;\n    constructor()\n    {\n        this.engine = new Engine();\n        this.tires = new Tires ();\n}\n}\n```\nWith DI\n```\nclass Car{\n    engine;\n    tires;\n    constructor(engine, tires)\n    {\n        this.engine = engine;\n        this.tires = tires;\n    }\n```\n}\n```\n\n```\nvar myEngine = new Engine();\nvar myTires = new Tires ();|\nvar myCar = new Car(myEngine, myTires);\n```\n\n```\nvar myEngine = new Engine(parameter);\nvar myTires = new Tires ();|\nvar myCar = new Car(myEngine, myTires);\n```\n\n```\nvar myEngine = new Engine(parameter);\nvar myTires = new Tires(parameter);\nvar myCar = new Car(myEngine, myTires);|\n```\nWe can mock the data to suit our testing needs \n```\nvar oldEngine = new Engine(oldparameter);\nvar oldTires = new Tires(oldparameter);\nvar oldCar = new Car(oldEngine, old|Tires);\n//test with oldCar\n```\n```\nvar newEngine = new Engine(newparameter);\nvar newTires = new Tires(newparameter);\nvar newCar = new Car(newEngine, new|tires);\n//test with newCar\n```\nwhen the number of dependencies grows, it becomes really difficult to manage the code.\n```\nvar myEngine = new Engine();\nvar myTires = new Tires();\nvar depA = new dependency ();\nvar depB = new dependency ();\nvar depZ = new dependency ();\nvar myCar = new Car (myEngine, myTires, depA, depB. debZ);|\n```\n```\nvar myEngine = new Engine();\nvar myTires = new Tires();\nvar depA = new dependency();\nvar depB = new dependency();|\nvar depAB = new dependency();\nvar depZ = new dependency (depAB);\nvar myCar = new Car(myEngine, myTires, depA, depB, depZ);\n```\nDI as a framework  \nInjector  \nEngine   ServiceA  \nTires    ServiceB  \nDepA     ServiceC  \nDepB     ..  \n...     ...  \n...    ...  \nDepZ     ServiceZ\n\nDI as a framework contd\n1. Define the EmployeeService class\n2. Register with Injector\n3. Declare as dependency in EmpList and EmpDetail\n    EmployeeService      injector\n    ↓　　　　　　　　↓\nEmpList        EmpDetail\n\n**Using a Service**\nhttps://www.youtube.com/watch?v=69VeYoKzL6I\n```\nng g s employee\n```\nemployee.service.ts\n```\nimport { Injectable } from '@angular/core';\n\n@Injectable()\nexport class EmployeeService{\n\n    constructor() {}\n\n    getEmployees(){\n     return [\n        {\"id\":1, \"name\": \"Andrew\", \"age\": 30},\n        {\"id\":2, \"name\": \"Brandon\", \"age\":25},\n        {\"id\":3, \"name\": \"Christina\", \"age\":26},\n        {\"id\":4, \"name\": \"Elena\", \"age\":28}\n];\n}\n}\n```\nemployee-list.component.ts\n```\nexport class EmployeeListComponent implements OnInit {\n\n    public employees = [\n     {\"id\":1, \"name\": \"Andrew\", \"age\": 30},\n        {\"id\":2, \"name\": \"Brandon\", \"age\":25},\n        {\"id\":3, \"name\": \"Christina\", \"age\":26},\n        {\"id\":4, \"name\": \"Elena\", \"age\":28}\n    ];\n\n    constructor() {}\n\n    ngOnInit(){\n    }\n}\n```\nemployee-detail.component.ts\n```\nexport class EmployeeDetailComponent implements OnInit {\n    public employees = [\n         {\"id\":1, \"name\": \"Andrew\", \"age\": 30},\n        {\"id\":2, \"name\": \"Brandon\", \"age\":25},\n        {\"id\":3, \"name\": \"Christina\", \"age\":26},\n        {\"id\":4, \"name\": \"Elena\", \"age\":28}\n    ];\n\n    constructor(){}\n\n    ngOnInit(){\n    }\n}\n```\nAppModule (Register)  \n  ↓\nAppComponent  \n  ↓         ↓\nEmpList   EmpDetail\n  ↓\nChild\n  ↓\nChild\n\napp.module.ts\n```\nimport { EmployeeService } from './employee.service';\n\n@NgModule({\n\n .....\n imports: [\n  BrowserModule\n  ],\n providers: [ EmployeeService],\n bootstrap: ....  \n   \nemployee-list.component.ts\n```\nimport {EmployeeService}\n\nexport class EmployeeListComponent implements OnInit {\n\n    public employees = [ ];\n\n    constructor(private_employeeService: EmployeeService) {}\n\n    ngOnInit(){\n        this.employees = this._employeeService.getEmployees();\n    }\n}\n```\nemployee-detail.component.ts\n```\nexport class EmployeeDetailComponent implements OnInit {\n    public employees = [ ];\n\n    constructor(private _employeeService: EmployeeService){}\n\n    ngOnInit(){\n        this.employees = this.employeeService.getEmployees();\n    }\n}\n```\nHTTP and Observables  \nhttps://www.youtube.com/watch?v=vj0kUzKOgGQ  \nObservables  \nA sequence of items that arrive asychronously over time.  \nHTTP call - single item  \nSingle item - HTTP response  \n  \nHTTP, Observables and RxJS  \n1. HTTP Get request from EmpService\n2. Receive the observable and cast it into and employee array\n3. Subscribe to the observable from EmpList and EmpDetail\n4. Assign the employee array to a local variable\n  \nRxJS  \n- Reactive Extensions for Javascript\n- External library to work with Observables\n\n**Fetch Data Using HTTP**  \nhttps://www.youtube.com/watch?v=LmIsbzt-S_E  \napp.module.ts\n```\nimport { HttpClientModule } from '@angular/common/http';\n\n...\n\n@NgModule({\n ...\n\n imports: [\n    BrowserModule,\n    HttpClientModule\n]\n```\nemployee.service.ts\n```\nimport { Injectable } from '@angular/core';\nimport { HttpClient } from '@angular/common/http';\n\n@Injectable()\nexport class EmployeeService{\n\n    constructor(private http: HttpClient) {}\n\n    getEmployees(){\n     return [\n        {\"id\":1, \"name\": \"Andrew\", \"age\": 30},\n        {\"id\":2, \"name\": \"Brandon\", \"age\":25},\n        {\"id\":3, \"name\": \"Christina\", \"age\":26},\n        {\"id\":4, \"name\": \"Elena\", \"age\":28}\n];\n}\n}\n```\n\nBootstrap\n```\nnpm install bootstrap --save\n npm i jquery popper.js --save\n```\n2.angular.json --\u003e architect\n```\n            \"styles\": [\n              \"src/styles.css\", \n              \"./node_modules/bootstrap/dist/css/bootstrap.min.css\"\n\n            ],\n            \"scripts\": [\n              \"./node_modules/jquery/dist/jquery.min.js\",\n              \"./node_modules/popper.js/dist/umd/popper.min.js\",\n              \"./node_modules/bootstrap/dist/js/bootstrap.min.js\"\n            ]\n```\n\n\n\nhttps://www.youtube.com/watch?v=soInCF7nbDw\u0026t=11209s\n\nhttps://codechord.com/2012/01/readme-markdown/\n\nhttps://docs.github.com/ja/get-started/writing-on-github/getting-started-with-writing-and-formatting-on-github/basic-writing-and-formatting-syntax  \n\nhttps://code.visualstudio.com/docs/nodejs/angular-tutorial\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnaopeke%2Fangular_commands","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnaopeke%2Fangular_commands","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnaopeke%2Fangular_commands/lists"}