0% found this document useful (0 votes)
5 views9 pages

Crud Angular - Net Core - Angular-Material

The document provides a comprehensive guide on integrating Angular Material into an Angular application, including installation, component setup, and working with tables. It covers how to add features such as pagination, CRUD operations, and displaying data from a backend service. Additionally, it includes code snippets for creating components, handling data, and utilizing Angular Material UI elements effectively.

Uploaded by

FabioOrtiz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views9 pages

Crud Angular - Net Core - Angular-Material

The document provides a comprehensive guide on integrating Angular Material into an Angular application, including installation, component setup, and working with tables. It covers how to add features such as pagination, CRUD operations, and displaying data from a backend service. Additionally, it includes code snippets for creating components, handling data, and utilizing Angular Material UI elements effectively.

Uploaded by

FabioOrtiz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

sqlCommand.Parameters.

Add(“@nombre”,nombre );

sqlCommand.ExecuteNonQuery();

ANGULAR MATERIAL UI

INSTALAR ANGULAR MATERIAL

ng add @angular/material

VISUALIZAR COMPONENTES

App.Module.ts

import { MatSlideToggleModule } from '@angular/material/slide-toggle';

@NgModule ({

imports: [

MatSlideToggleModule,

})

class AppModule {}

Agrega el selector en el componente de angular correspondiente:

<mat-slide-toggle>Toggle me!</mat-slide-toggle>

TRABAJANDO CON TABLAS DE ANGULAR/MATERIAL

1. Agregar Referencia API a app.module.ts

import {MatTableModule} from '@angular/material/table';


2. Seleccionar el código HTML y pegarlo en el HTML
correspondiente

<table mat-table [dataSource]="dataSource" class="mat-elevation-z8">

<!--- Note that these columns can be defined in any order.


The actual rendered columns are set as a property on the row
definition" -->

<!-- Position Column -->


<ng-container matColumnDef="position">
<th mat-header-cell *matHeaderCellDef> No. </th>
<td mat-cell *matCellDef="let element"> {{element.position}} </td>
</ng-container>

<!-- Name Column -->


<ng-container matColumnDef="name">
<th mat-header-cell *matHeaderCellDef> Name </th>
<td mat-cell *matCellDef="let element"> {{element.name}} </td>
</ng-container>

<!-- Weight Column -->


<ng-container matColumnDef="weight">
<th mat-header-cell *matHeaderCellDef> Weight </th>
<td mat-cell *matCellDef="let element"> {{element.weight}} </td>
</ng-container>

<!-- Symbol Column -->


<ng-container matColumnDef="symbol">
<th mat-header-cell *matHeaderCellDef> Symbol </th>
<td mat-cell *matCellDef="let element"> {{element.symbol}} </td>
</ng-container>

<tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>


<tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

3. Copiar el .Ts y pegarlo en el archivo correspondiente:

import {Component} from '@angular/core';

export interface PeriodicElement {


name: string;
position: number;
weight: number;
symbol: string;
}

const ELEMENT_DATA: PeriodicElement[] = [


{position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
{position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'},
{position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'},
{position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be'},
{position: 5, name: 'Boron', weight: 10.811, symbol: 'B'},
{position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C'},
{position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N'},
{position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O'},
{position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F'},
{position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne'},
];

/**
* @title Basic use of `<table mat-table>`
*/
@Component({
selector: 'table-basic-example',
styleUrls: ['table-basic-example.css'],
templateUrl: 'table-basic-example.html',
})
export class TableBasicExample {
displayedColumns: string[] = ['position', 'name', 'weight',
'symbol'];
dataSource = ELEMENT_DATA;
}

4. Copiar y pegar el .css donde corresponda

table {
width: 100%;
}

Agregando Paginador

1. Agregar al app.module.ts

import {MatPaginatorModule} from '@angular/material/paginator';

2. Agregar al HTML correspondiente(anterior)

<mat-paginator [pageSizeOptions]="[5, 10, 20]"


showFirstLastButtons
aria-label="Select page of periodic elements">
</mat-paginator>

3. Agregar al .ts correspondiente(Anterior)

import {AfterViewInit, Component, ViewChild} from '@angular/core';


import {MatPaginator} from '@angular/material/paginator';
import {MatTableDataSource} from '@angular/material/table';

export class TablePaginationExample implements AfterViewInit {


displayedColumns: string[] = ['position', 'name', 'weight',
'symbol'];
dataSource = new MatTableDataSource<PeriodicElement>(ELEMENT_DATA);

@ViewChild(MatPaginator) paginator!: MatPaginator;


ngAfterViewInit() {
this.dataSource.paginator = this.paginator;
}
}

@ViewChild: usa ViewChild para acceder a una directiva, componente secundario y a un


elemento DOM desde una clase principal de componentes. Si la referencia cambia a un nuevo
elemento dinámicamente, ViewChild actualizará automáticamente su referencia.

ngAfterViewInit: se ejecuta después del render. En este se manejan de forma programática los
hijos del componente.

MOSTRAR DATOS DESDE NUESTRO BACKEND

import { Tipos } from 'src/app/Models/tipos';


import { InspectionTypeService } from 'src/app/service/inspection-
type.service';

const tipos: Tipos[] = [];

@Component({
selector: 'app-tipos',
templateUrl: './tipos.component.html',
styleUrls: ['./tipos.component.css']
})
export class TiposComponent {
displayedColumns: string[] = ['id',
'nombre','responsable','acciones'];
dataSource = new MatTableDataSource<Tipos>(tipos);
@ViewChild(MatPaginator) paginator!: MatPaginator;

constructor(private inspectiontypeservice: InspectionTypeService){


this.inspectiontypeservice.getInspectionType().subscribe(res =>{
console.log(res);
this.dataSource.data = res;
});
}

ngOnInit(){

ngAfterViewInit() {
this.dataSource.paginator = this.paginator;
}
}

Subscribe() es un método en Angular que conecta el observer con


eventos observable. Siempre que se realiza algún cambio en estos
observables, se ejecuta un código y observa los resultados o cambios
mediante el método subscribe. Subscribe() es un método de la
biblioteca rxjs, utilizado internamente por Angular.

AGREGANDO OPERACIONES(CRUD) AL LISTADO .HTML

En el .html anterior agregar la nueva columna acciones

<ng-container matColumnDef="acciones">
<th mat-header-cell *matHeaderCellDef> Acciones </th>
<td mat-cell *matCellDef="let element">
<mat-icon class="search" matTooltip="Ver"
fontIcon="search" routerLink="/getInspection/{{element.id}}"></mat-
icon>
<mat-icon class="edit" matTooltip="Editar"
fontIcon="edit"></mat-icon>
<mat-icon class="delete"
matTooltip="Borrar"fontIcon="delete"
(onclick)=”eliminarMascota(element.id)”></mat-icon>
</td>

Agregar al app.moudule.ts

import {MatIconModule} from '@angular/material/icon';


import {MatTooltipModule} from '@angular/material/tooltip';

const routes: Routes = [{‘getInspection/:id’, component:


appDetalleComponent}]

CREAR COMPONENTE DETALLE

Ng g c Components/detalle

import { Component } from '@angular/core';


import { ActivatedRoute } from '@angular/router';
import { InspectionTypeService } from 'src/app/service/inspection-
type.service';
import { Tipos } from 'src/app/Models/tipos';
import { Observable } from 'rxjs';

@Component({
selector: 'app-detalle',
templateUrl: './detalle.component.html',
styleUrls: ['./detalle.component.css']
})
export class DetalleComponent {
id!:number;
inspeccion!: Tipos;
inspeccion$! :Observable<Tipos>;
constructor(private inspectiontypeservice: InspectionTypeService,
private activatedRoute: ActivatedRoute){
this.id = +this.activatedRoute.snapshot.paramMap.get('id')!;
}

ngOnInit(){
//this.getInspectionById();
this.inspeccion$ =
this.inspectiontypeservice.getInspectionTypebyId(this.id);
}
getInspectionById(){
/* return
this.inspectiontypeservice.getInspectionTypebyId(this.id).subscribe(d
ata=>{
this.inspeccion = data;
})*/
}

Detalle.html

<mat-card>
<div *ngIf="inspeccion$ | async as inspeccion" class="container
text-center">
<!-- <div *ngIf="inspeccion != null" class="container text-
center">
-->
<mat-card-title>Id: {{inspeccion.id}}</mat-card-title>
<mat-card-content>
<h3>Nombre: {{inspeccion.nombre}}</h3>
<h3>Responsable: {{inspeccion.responsable}}</h3>
</mat-card-content>
</div>
</mat-card>

ELIMINAR

constructor(private inspectiontypeservice: InspectionTypeService){


}

ngOnInit(){
getTipos();
}

getTipos(){

this.inspectiontypeservice.getInspectionType().subscribe(res =>{
console.log(res);
this.dataSource.data = res;
});

eliminarMascota(id:number){
return
this.inspectiontypeservice.deleteinspectionType(id).subscribe(data=>{
/*this.toast.success('Registro eliminado satisfactoriamente!');*/
alert('Delete')
this.getTipos();
})
}

AGREGAR

Ng g c Components/add-tipos
App.module.ts
import {MatGridListModule} from '@angular/material/grid-list';
import {MatFormFieldModule} from '@angular/material/form-field';
import {MatInputModule} from '@angular/material/input';

{path:'AgregarTipos', component : AddTiposComponent}

Html

<div class="title text-center">


<h3>Agregar Tipos De Inspeccion</h3>
</div>
<div class="container">
<mat-card>
<mat-card-subtitle>Datos Tipo Inspeccion</mat-card-subtitle>
<form>
<mat-grid-list cols="2" rowHeight="80px">
<mat-grid-tile [colspan]="2">
<mat-form-field appearance="outline" class="mat-form-
field">
<mat-label>Nombre</mat-label>
<input matInput autocomplete="off">
</mat-form-field>
</mat-grid-tile >
<mat-grid-tile [colspan]="2">
<mat-form-field appearance="outline" class="mat-form-
field">
<mat-label>Responsable</mat-label>
<input matInput autocomplete="off">
</mat-form-field>
</mat-grid-tile>
<mat-grid-tile [colspan]="2">
<button mat-button color="secondary">Aceptar</button>
<button mat-button color="primary">Regresar</button>
</mat-grid-tile>
</mat-grid-list>
</form>
</mat-card>
</div>

.ts

.appmodule.ts

Import { ReactiveFormsModule} from ‘@angular/core’

You might also like