0

estoy teniendo un problema con material ui en angular, al insertar un dialog no logro hacer que tome la id del elemento, probe con diferentes respuestas que encontre aca y hasta ahora no logro conectar por id el dialog con ninguna, esto es lo que tengo hasta ahora:

este seria el ts del elemento principal, donde esta el boton que abre el dialog

import { Component, EventEmitter, OnInit, Output } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { EducationService } from 'src/app/services/education.service';
import { DialogContentEditEducation } from './edit/editedu.component';

@Component({
  selector: 'app-education',
  templateUrl: './education.component.html',
  styleUrls: ['../hero-content/hero-content.component.css']
})
export class EducationComponent implements OnInit {
  @Output() public sidenavToggle = new EventEmitter();
  educations: any=[];
  constructor(private educationService: EducationService, public dialog: MatDialog) { }

  openDialog() {
    const dialogRef = this.dialog.open(DialogContentEditEducation);
  }

  ngOnInit(): void {
    this.listarEducation();
  }

  listarEducation()
  {
    this.educationService.getEducation().subscribe(
      res=>{
        this.educations=res;
        console.log(res);
      },
      err=>console.log(err)
    );

  }

  eliminar(id:string)
  {
    this.educationService.deleteEducation(id).subscribe(
      res=>{this.ngOnInit();},
      err=>console.log(err)
    );
  }
}

este seria el html del boton que abre el dialog

<button mat-mini-fab color="primary" (click)="openDialog()" matTooltip="Modificar">

este seria el servicio conectado a la api

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class EducationService {
  url='http://localhost:8080/api/education';
  constructor(private http: HttpClient) { }
  
  getEducation():Observable<any>
  {
    return this.http.get(this.url)
  }

  getOneEducation(id: string):Observable<any>
  {
    return this.http.get(this.url+'/'+id);
  }

  saveEducation(education: Education):Observable<any>
  {
    return this.http.post(this.url, education);
  }

  editEducation(id: string, education: Education):Observable<any>
  {
    return this.http.put(this.url+'/'+id, education);
  }

  deleteEducation(id: string):Observable<any>
  {
    return this.http.delete(this.url+'/'+id);
  }
}

export interface Education {
  id?: string,
  year1: string,
  year2: string,
  level: string;
  place: string,
  dtexto: string
}

este seria el ts del componente que abre el dialog

import { Component, OnInit, Output, EventEmitter } from '@angular/core';
import {FormControl, FormGroup, Validators} from '@angular/forms';
import { EducationService, Education } from 'src/app/services/education.service';
@Component({
  selector: 'dialog-content-edit-education',
  templateUrl: './editedu.component.html',
  styleUrls: ['./editedu.component.css']
})
export class DialogContentEditEducation {
  range = new FormGroup({
    year1: new FormControl(),
    year2: new FormControl(),
  });
  id:string="";
  educationActual: Education={id:'',year1:'',year2:'',level:'',place:'',dtexto:''};
  constructor(
    private educationService:EducationService,
    ) { }
    ngOnInit(): void {
      this.educationService.getOneEducation(this.id).subscribe(
        res=>{
          this.educationActual=res;
        },
  
        err=>console.log(err)
      );
    }
    
    guardad(){
      this.educationService.editEducation(this.id, this.educationActual).subscribe(
        res=>{
          console.log
        },
  
        err=>console.log(err)
      );
    }
}

y por ultimo el html del componente que abre el dialog

<h2>Editar educación</h2>
<mat-form-field class="full-width" appearance="fill">
  <mat-label>Duración</mat-label>
  <mat-date-range-input [formGroup]="range" [rangePicker]="picker">
    <input matStartDate id="year1" [(ngModel)]="educationActual.year1" formControlName="year1" placeholder="Inicio">
    <input matEndDate id="year2"[(ngModel)]="educationActual.year2" formControlName="year2" placeholder="Fin">
  </mat-date-range-input>
  <mat-hint>MM/DD/YYYY – MM/DD/YYYY</mat-hint>
  <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
  <mat-date-range-picker #picker></mat-date-range-picker>
</mat-form-field>
<mat-form-field class="full-width">
  <input type="text" id="level" name="level" [(ngModel)]="educationActual.level" matInput placeholder="Nivel de educacion">
</mat-form-field>
<mat-form-field class="full-width">
  <input type="text" id="place" name="place" [(ngModel)]="educationActual.place" matInput placeholder="Lugar">
</mat-form-field>
<mat-form-field class="full-width">
  <textarea  type="dtexto" id="dtexto" name="place" [(ngModel)]="educationActual.dtexto" matInput placeholder="Descripción"></textarea>
</mat-form-field>
<button (click)="guardad()" mat-raised-button color="primary">Guardar</button>

gracias de ante mano!

1
  • Podes compartir data con tu componente dialogo mediante MAT_DIALOG_DATA en tu dialog tu id es un string vacio
    – nestdan
    el 24 abr. 2022 a las 21:37

1 respuesta 1

1

comunicas Modales usando MAT_DIALOG_DATA asi:

Componente que dispara el dialogo:

openDialog() {
  const dialogRef = this.dialog.open(DialogContentEditEducation, {data: 
  idEnviado});
}

Dialogo que se abre:

import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
.
.
.
 constructor(
   public dialogo: MatDialogRef<TuDialogoComponent>,
   @Inject(MAT_DIALOG_DATA) public data: string
  ) { }

Asi la variable data contendra la informacion que deseas comunicar.. y adicional mente si quizas quieres enviar info de vuelta:

 close(): void {
  this.dialogo.close(/data que quieres emitir al cerrar el modal/);
 }

y la capturas como un observable en el metodo inicial que disparo el modal:

openDialog() {
   const dialogRef = this.dialog.open(DialogContentEditEducation, {data: 
   idEnviado});

   dialogRef.afterClosed().subscribe(data => {//data llegando de respuesta 
   al cerrar el modal});
 }

Espero te sea de ayuda.

Happy Coding!

Tu Respuesta

Al pulsar en “Publica tu respuesta”, muestras tu consentimiento a nuestros términos de servicio, política de privacidad y política de cookies

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.