Managing data in an Angular Material table and dialog for creating, reading

Currently, I am struggling with implementing a CRUD method using angular material table and dialog components. I am facing difficulties in understanding how to update records using the dialog and pass data between components.

Despite my efforts, the modify line is not updating as expected. Can anyone shed some light on what might be wrong with my code?

Thank you!

service

  getTableDetails(): Observable<any[]> {
    return this.http.get<any[]>(this.url);
  }

  create(name: any): Observable<any> {
    return this.http.post<any>(this.url, name);
  }

  update(id: any, data: any): Observable<any> {
    return this.http.put<any>(this.url + '/' + id, data);
  }

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

ts.file

  openDialog(element: any) {
    const dialogRef = this.dialog.open(EditTableDialogComponent, {
      data: element,
    });

    dialogRef.afterClosed().subscribe(result => {
      console.log(`Dialog result: ${result}`);
    });
  }

dialog.html

<div class="inputAdd">
  <h2>Edit Table</h2>
  <input #input value="{{element.name}}" required>
  <button (click)="edit(input.value)">Modifier</button>
</div>

dialog.ts

export class EditDialogComponent {
  constructor(
    @Inject(MAT_DIALOG_DATA) public data: MatDialog,
    private tableService: TableService
  ) {}

  public element: any = this.data;

  edit(value: any) {
    this.tableService.update(this.element.id, value).subscribe((data:any) => {
      console.log(data);
    });
  }
}

Answer №1

In my opinion, it is not advisable to handle the update or creation of an item within the dialog component. The dialog component should focus solely on allowing the user to make changes to the entity. Trying to incorporate such responsibilities within the dialog component can lead to difficulties in maintenance. Instead, upon closing the modal, you can listen for the afterClosed event and determine the appropriate action for the entity. Typically, if the entity has an id, it suggests that an existing entry should be updated, otherwise, a new one should be created.

Additionally, the dialog component should have access to dialogRef for closing the dialog and providing a result:

export class EditDialogComponent {
  constructor(
    @Inject(MAT_DIALOG_DATA) public data: MatDialog,
    private tableService: TableService,
    private dialogRef: MatDialogRef<EditDialogComponent>
  ) {}

  public element: any = this.data;

  edit(value: any) {
    this.dialogRef.close(this.element);
  }
}

In the component responsible for rendering the table, the modal should be opened as usual:

openDialog(element: any) {
  const dialogRef = this.dialog.open(EditTableDialogComponent, {
    data: element,
  });
  dialogRef
    .afterClosed()
    .pipe(
      filter((element) => !!element), // in case the user closes the modal without pressing the "Modifier" button
      switchMap(
        (element) => iif(() => element.id),
        this.tableService.update(element.id, element),
        this.tableService.create(element)
      )
    )
    .subscribe((data) => {
      console.log('success', data);
    });
}

Finally, determine whether to create a new item or update an existing one.

Answer №2

When working on your component, consider utilizing Formbuilder and input.getValue()

<div [formGroup]="formInput" class="inputAdd">
  <h2>Edit Table</h2>
  <input #input value="{{element.name}}" formControlName="myInput">
  <button (click)="edit(input.value)">Modify</button>
</div>

in TS

constructor(private formBuilder: FormBuilder) { }

createForm() {
    this.formInput = this.formBuilder.group({
      myInput: [cliente.name],
    })
  }

edit(value: any) {
    sendValue = this.createForm.myInput.getValue;
    this.tableService.update(this.element.id, sandValue).subscribe((data:any) => {
      console.log(data);
    });
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Understanding the Difference Between WARN and ERR in npm Peer Dependency Resolution

I encountered a puzzling situation where two projects faced the same issue, yet npm resolved them differently: https://github.com/Sairyss/domain-driven-hexagon npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! W ...

Unexpected absence of Aria tags noticed

I've been working on integrating ngAria into my project. I have injected it into my module and created the following HTML: First Name: <input role="textbox" type="text" ng-model="firstName" aria-label="First Name" required><br> Employee: ...

Choosing an option beforehand using angular-ui-select2 version 0.0.5

I'm struggling with setting a default option in a select2 dropdown using Angular and an ng-model. Here's my implementation: Angular controller code snippet $scope.filter = { searchValue: '', departmentId: 'Department2' } ...

React automatic scrolling

I am currently working on implementing lazy loading for the product list. I have created a simulated asynchronous request to the server. Users should be able to update the page by scrolling even when all items have been displayed. The issue arises when ...

How can I change a time duration (e.g. 3 hours 23 minutes) to a specific date and time in

Is there a way to transform a time string such as 2h 25m 15s or 2h 10m into a datetime, or simply convert it to minutes like 1h => 60, using NodeJS? ...

Tips for enabling selection of list items in an input tag

Below is the code I have written to create an InputFilter. MyFilter = function(args) { var dataUrl = args.url; var divID = args.divID; var div = document.getElementById(divID); var myTable = '<input type="text" id="myInput" on ...

Error: anticipated expression, received keyword 'if'

I'm facing an issue that I could really use some assistance with. I am trying to hide the "changeOrderUp" button when it's in the first row, and similarly, I want to hide the "changeOrderDown" button when it's in the last row. However, FireB ...

Is it possible to convert a blob to an image file using the FileReader in HTML

client side code <head> <script> var reader = new FileReader(); var objVal; var image = new Image(); reader.onload = function(e) { document.getElementById('propertyImg').setAttribute('src', e.target.result); }; fun ...

Create a bookmarklet for Webdriver when initializing the driver, or store the bookmarklet in your saved bookmarks, all done without the need to

Need Help Adding Custom Bookmarklet to Webdriver I am looking for a way to include a custom bookmarklet (a bookmark that consists of pure JavaScript code) in a webdriver so it appears on the bookmarks toolbar. I would like to achieve this either during th ...

React/Express: Error 413 encountered when posting due to payload size exceeding limit and Bodyparser failing to handle it

I've exhausted all options but this issue seems unsolvable. I have scoured every single suggested fix on stackoverflow and gone through 3 pages of Google search results. Methods I've attempted Inserted extended: true/false in bodyParser.json U ...

Rendering React.js components as children of DOM elements

Trying my hand at creating a custom Map component includes the task of designing a unique Map Annotation. Here's an example of how a MapAnnotation component appears in the render function: <MapAnnotation title='Annotation' latitude={ 12.3 ...

Testing API route handlers function in Next.js with Jest

Here is a health check function that I am working with: export default function handler(req, res) { res.status(200).json({ message: "Hello from Next.js!" }); } Alongside this function, there is a test in place: import handler from "./heal ...

Ways to showcase a JavaScript popup on an Android WebView

Can a JavaScript popup window be opened on an Android web viewer that is coded similarly to this example from Google? If so, how can this be accomplished without closing the original background page and ensuring it resembles a popup as shown in the picture ...

Sporadic UnhandledPromiseRejectionWarning surfacing while utilizing sinon

Upon inspection, it appears that the objects failApiClient and explicitFailApiClient should be of the same type. When logging them, they seem to have identical outputs: console.log(failApiClient) // { getObjects: [Function: getObjects] } console.log(expli ...

How can I alter the color of the menu text when scrolling to the top of a webpage?

As I navigate my website, I encounter a menu with a transparent background at the top that changes to black as I scroll down. On a specific page where the background is white, this presents an issue: when the menu reaches the top, the white background clas ...

Assign an event listener to a collection of elements

Suppose I have an Array containing elements and another Array consisting of objects in the exact same index order. My goal is to add a click event for each element that will display a specific property of each object. For instance: myDivArray = [ div0, d ...

Minimize or conceal iframe

This iframe contains a Google form that cannot be edited. I am looking for a way to close or hide this iframe, either through a button, a popup window button, or without any button at all. The $gLink variable holds the Google form link through a PHP sessio ...

Stop the spread - Touch to choose - React with Material Design

I am currently utilizing ReactJS along with the library @material-ui/core. In my code, I am seeking to halt event propagation on Click. Here is the snippet: <NumPad.Number onChange={val => { this.setPrice(val) } }> <TextField ...

Get canvas picture through JS Jquery

I've been attempting to save a canvas image to my desktop using this code: <script type="text/javascript"> var canvas; $(document).ready(function() { if ($('#designs-wrapper').length) { $('.design').eac ...

Error: Trying to access "dishes" property on an undefined object gives a TypeError

Need Assistance Urgently! I have developed a web application using react and integrated it with node js. In the app, I am required to pass the status of a dish to the DishDetail Component indicating whether it is marked as "Favorite" or not. If a dish is ...