Updating the model in Angular 2 using two-way binding

I am looking to make some updates to my Angular 2 model.

Here is my update method:

  putDep(item) {
   var headers = new Headers();
   headers.append('Content-Type', 'application/json');

    this.selected.departmentName = item.departmentName;
    this.selected.departmentLocation = item.departmentLocation;

  return this.http.put('http://localhost:65402/company/api/department'+ "/update/" + this.selected.departmentNo,  JSON.stringify(item),{headers: headers})
                  .subscribe(res => {this.departments = res.json();});

}

And here is the HTML code snippet:

 <form  #selected="ngForm" [hidden]="!showEditView" align="center">
    <div>
        <label for="editAbrv">Department No:</label><br>
        <input ngControl="departmentNo" placeholder="name">
    </div>
    <div>
        <label for="editAbrv">Department name:</label><br>
        <input ngControl="departmentName" placeholder="name">
    </div>
    <div>
        <label for="editAbrv">Department Location:</label><br>
        <input ngControl="departmentLocation" placeholder="location">
    </div>

    <div>
        <a href="javascript:void(0);" (click)="putDep(selected.value)" title="Add">
            Save
        </a>
        <a href="javascript:void(0);" (click)=showHide($event) >
            Cancel
        </a>
    </div>
</form>

I am facing an issue with two-way binding with the model. Here is how it is handled in the backend:

  [HttpPut]
            [Route("Update/{id}")]
            public async Task<HttpResponseMessage> Update(int id, DepartmentModel model)

The problem I am encountering is that when I try to edit the model, the integer id is passed to the backend but the model id (which should match the passed id) is null. Additionally, when I click on the edit button, I am unable to see any changes on the view when I input values for the model. I was able to quickly solve this issue in Angular 1, but Angular 2 has proven to be more challenging. My goal is to have the id automatically connected to my model when I click edit and to see it displayed in the input field along with the other two properties. Any help or guidance would be greatly appreciated! Thank you!

Answer №1

To resolve this issue, I recommend utilizing the ngModel directive. By selecting an element, you can assign a property called selectedDepartment within your component to contain the department that needs updating. You can then bind specific properties of this object to the input fields (only those properties that require updating).

The selectedDepartment object should encompass all relevant properties, including the current identifier.

Instead of submitting the form value when clicking the "Save" button, you could send this object instead. This approach ensures that the identifier information is retained.

Below is the code snippet for the form:

<form  #selected="ngForm" [hidden]="!showEditView" align="center">
  <div>
    <label for="editAbrv">Department No:</label><br>
    <input [(ngForm)]="selectedDepartment.departmentNo" ngControl="departmentNo" placeholder="name">
  </div>
  <div>
    <label for="editAbrv">Department name:</label><br>
    <input [(ngForm)]="selectedDepartment.departmentName" ngControl="departmentName" placeholder="name">
  </div>
  <div>
    <label for="editAbrv">Department Location:</label><br>
    <input [(ngForm)]="selectedDepartment.departmentLocation" ngControl="departmentLocation" placeholder="location">
  </div>

  <div>
    <a href="javascript:void(0);" (click)="putDep(selectedDepartment)" title="Add">
      Save
    </a>
    <a href="javascript:void(0);" (click)=showHide($event) >
      Cancel
    </a>
  </div>
</form>

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

Angular4 ASP.NET Core project does not seem to be detecting the API endpoints

I am encountering an issue with my angular application where I consistently receive a "Cannot match any routes" error when attempting to access certain api resources. The base in my application is configured as <base href="/"> and the api source is ...

Incorporating data types into a constant in Typescript/Javascript

Imagine I wanted to ensure these variables are string objects by adding a type string declaration to this variable assignment. What is the correct way to accomplish this? const { someID, someName, someAPIenvironment } = useParams(); This is what I attemp ...

Transform the blob data into an Excel file for easy download, but beware the file is not accessible

My API returns a response containing the content of an excel file, which is displayed in the image below. https://i.sstatic.net/2VHsL.png Now, I am looking to convert this content into an excel file and make it downloadable for the user. Below is the AP ...

I am struggling with setting the data received from the backend to an array variable in Angular

Looking for assistance with my interface and service files: [Click here to view the service file code image](https://i.sstatic.net/2f0bzkDM.png) Upon executing the request to retrieve data from the backend and assign it to the variable 'users', ...

Having trouble deleting multiple rows with ng-repeat in datatables

Having followed the instructions in this post, I quickly integrated it with jquery datatables. However, the functionality is not as expected. When attempting to delete rows, they do not get deleted. Furthermore, if I navigate to the next page and return, ...

The broadcast message from AngularJS (1.2.25) $rootScope.$broadcast('message', data) appears to be failing to reach the corresponding $scope.$on('message') listener

I'm struggling with getting a $scope variable to trigger the screen to rebind. I have attempted calling $scope.$apply() and $digest() after assigning $scope.value = value, but I encounter an error "$rootScope:inprog] $digest already in progress. To t ...

Modify the ngb-timepicker formatting to output a string instead of an object

I am currently working on modifying ngb-timepicker so that it returns a string instead of an object. Right now, it is returning the following format: { "hour": 13, "minute": 30 } However, I want it to return in this format: "13:30" This is the HTM ...

Implementing delayed loading of Angular modules without relying on the route prefix

In my application, I am using lazy loading to load a module called lazy. The module is lazily loaded like this: { path:'lazy', loadChildren: './lazy/lazy.module#LazyModule' } Within the lazy module, there are several routes def ...

A tutorial on implementing a "Back to Top" button that appears dynamically while scrolling in Angular

I've developed a scroll-to-top feature for my Angular project, but I'm facing an issue. The scroll icon appears immediately upon page load instead of only showing after the user scrolls down. Any ideas or suggestions on how to achieve this? Here ...

Organization and Naming Standards for Projects

After exploring the Repeating module name for each module component issue, we have decided to adopt the organizational recommendations outlined in the Best Practice Recommendations for Angular App Structure blog post. This approach has been implemented in ...

Executing a function upon clicking the overlay label of jsPlumb in Angular 4

I'm currently using jsplumb in Angular 4 to establish connections between elements. I am also attempting to display a modal with dynamic content when the label of the jsplumb is clicked. Here is the code snippet: component.ts ngAfterViewInit() { ...

Liferay's JavaScript bundler does not automatically remove unused node modules

Within my work on Liferay 7.3.5 and developing an Angular Portlet, I have encountered a frustrating issue. When experimenting with different modules or versions of the same module, I noticed that the final jar OSGI module contains all the modules I have in ...

Guide on tracking the cursor using Angular

Recently, I developed a basic application in Angular that incorporates animations. You can check out the StackBlitz here to see it in action. The app features states that we can switch to control where an eye is looking. Currently, I am looking for a way ...

Best practices for stubbing an element in order to effectively unit test a LitElement component

Trying to perform unit tests on LitElement components has been quite a challenge for me. I found myself stuck when attempting to isolate components, particularly in figuring out how to stub elements effectively. The Polymer project provides some informatio ...

Angular app - static List mysteriously clears out upon refresh

My goal is to create a login page using Angular. I have an Angular component with HTML, CSS, and TypeScript files that manage this functionality. The HTML file contains two fields (Username and Password) and two buttons (Login and Register). When a user en ...

Exploring Angular 9: A guide to targeting a specific field within ng-select using ngFor

Recently, I've been diving into Angular and JS. In my code, I have implemented 3 ng-select elements using a ngFor loop. <div class="filter-input" *ngFor="let input of data; let i = index"> <div class=&q ...

Utilizing Angular for creating an accessible Bootstrap modal

Currently, I am utilizing Lighthouse to ensure the accessibility of my application. My goal is to enhance the accessibility of a Bootstrap modal. Here is the component's code: constructor(private modalService: NgbModal) {} let m = this.modalService.o ...

Tips for getting links to wrap or scroll within a column element in Angular

In my row element with two columns, I am facing an issue where the first column sometimes overlaps the second column due to a very long link in the problem.problem_description section. I want to find a way to have long links wrap or be scrollable. However, ...

Is it possible to utilize super class methods as decorator methods in Typescript?

I'm working on a project where I aim to create an easily extendible decorator factory, and achieving this would be a great accomplishment. The main goal is to utilize the methods of a superclass as decorators for properties in subclasses. This is ty ...

Accessing the OSRM API allows users to determine the distance to the closest emergency station

I am currently working on a typescript project where I need to calculate the distance to the nearest police station and fire station. My approach involves utilizing typescript for this task. Initially, I attempted to use the following URL that I discovere ...