Updating the content of text inputs within a form in Angular 2

Recently, I've been diving into Angular 2 and so far, I'm enjoying the experience. However, I could use some guidance to navigate this new territory.

One specific challenge I'm facing is with a form for editing user details and a list of users on the side. What I want to achieve is that when I click on a user in the list, the edit-user-form should be populated with that user's details (setEditForm(user)).

I have managed to make it work, but using ngControl and ngModel simultaneously doesn't feel quite right to me. Perhaps it is the correct approach, or maybe I just got lucky in getting it to work?

Can someone confirm if this is the appropriate method or if there is a better way to accomplish this task?

@Component({
  template: `
    <form (ngSubmit)="editUser(f.value)" #f="ngForm">
      <input ngControl="nameInp" [ngModel]="selectedUser.name" type="text">
      <input ngControl="ageInp" [ngModel]="selectedUser.age" type="text">
      <input ngControl="cityInp" [ngModel]="selectedUser.city" type="text">

      <button type="submit">Save</button>
    </form>
)}

export class AdminComponent {
 selectedUser:UserModel;

 constructor() {
    this.selectedUser = new UserModel;
  }

  setEditForm(user:UserModel) {
    this.selectedUser = user;
  }

  editUser(form:any) {
    // Update DB with values
    console.log(form['nameInp']);
    console.log(form['ageInp']);
    console.log(form['cityInp']);
  }
}

Answer №1

Absolutely, you have the ability to utilize both ngControl / ngFormControl and ngModel simultaneously. According to the Angular2 documentation (https://angular.io/docs/ts/latest/guide/forms.html):

  • Facilitating two-way data binding with [(ngModel)] syntax for managing input control values

  • Utilizing ngControl to monitor change state and form control validity

  • Presenting validation errors to users and enabling/disabling form controls

  • Exchanging information among controls using template local variables

In summary, I would opt for ngModel when requiring two-way binding and ngForm / ngFormControl for validation; however, they can be combined.

If your requirement is solely retrieving values and notifications upon input value updates, employing ngControl / ngFormControl` alone is sufficient...

Both options allow for change detection:

  • Event ngModelChange
  • Subscribing to ctrl.valueChanges

You could configure two-way binding for ngModel across your form elements:

<form (ngSubmit)="editUser(f.value)" #f="ngForm">
  <input ngControl="nameInp" [(ngModel)]="selectedUser.name" type="text">
  <input ngControl="ageInp" [(ngModel)]="selectedUser.age" type="text">
  <input ngControl="cityInp" [(ngModel)]="selectedUser.city" type="text">

  <button type="submit">Save</button>
</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

Tips for avoiding API calls at specific intervals while in the process of logging out from a web application

I have integrated a 60 second timer observable in my Ionic/Angular app, which emits the current time synchronized with the server time. Every minute, I fetch permissions, settings, and other data by passing a token with each request. Upon logout, I revoke ...

Please replace the text with only letters and then submit it without any spaces, periods, commas, or other symbols

Whenever I encounter a form like this, I need to submit it and replace the text in the name field with only letters - no commas, spaces, or special characters. https://i.sstatic.net/9FQnT.png myform.html <script> function fixInput(event) { na ...

Creating an array like this in JavaScript during an API call using Ajax

"WorkingHours": { "Monday" : { "open" : "10:00 am", "close" :"5:00 pm" }, "Wednesday" : { "open" : "10:00 am", "close" :"5:00 pm" ...

Commitment and follow through

I am encountering an issue in my Angular2 (ionic2) application. There seems to be a problem with the "subscribe" property not existing on this.cityService.getAllCities(). Within cityPage.ts, there is a function structured like this: getCities(){ this ...

TypeScript fails to recognize that the filtered array consists entirely of one type when using a type guard

I recently stumbled upon this code snippet in a coding playground where TypeScript is used: export interface Page { heading: string; component: string; path: string; } export type RouteOnly = Pick<Page, 'heading' | 'path'> ...

Using a Class Decorator in Typescript to Enhance Static Methods across all Classes

Imagine having a class filled with numerous static methods. The objective is to encapsulate each static method within a function. The specific aim is to handle async errors by applying .catch to every static method in the following manner: // Within user-r ...

The child element is absolutely positioned within the parent element with a higher z-index

It is crucial for the parent absolute to be under child absolute. How can I resolve this issue using CSS? The positions of both elements must remain absolute. <div class="parent"> <div class="child">child</div> </div> ...

javascript ondrag while self-pressing

Within this div, I have a series of p elements. My goal is to drag the selected element into the input field. Here's an example: var input = document.getElementById("test"); input.addEventListener('drop', function (event) { event.pr ...

Solve the issue of the header plugin malfunctioning on Angular datatables

I am currently implementing the stable build version Stable release v2.1.2 of the fixed header jquery plugin. My objective is to lock the header of a table in place. I have generated the table using Angular datatables as outlined on this source. Within my ...

Dynamic Bootstrap tooltip

I have a simple Javascript code snippet that I'm struggling with: $("#myinput").hover(function(){ if(condition){ $(this).tooltip({placement: "bottom", title: "mytitle"}); } ); Accompanied by its HTML cou ...

Pressing the submit button will not successfully forward the form

I've encountered an issue with my submit buttons - when I click on them, nothing happens. They were functioning properly before, but now they seem to be unresponsive. What could be causing this problem? <form id="contact" name="updateorder" acti ...

Object-oriented programming (OOP) implementation with asynchronous JavaScript and XML (

... I'm currently facing a situation where I have an object: function Page(daoService) { this.daoService = daoService; this.gamesList = this.daoService.getGamesList(); } // Rendering thumbs for main page Page.prototype.renderThumbs = functio ...

Limiting the style of an input element

How can I mask the input field within an <input type="text" /> tag to restrict the user to a specific format of [].[], with any number of characters allowed between the brackets? For example: "[Analysis].[Analysis]" or another instance: "[Analysi ...

Storing JSON data in a variable using .subscribe is not possible in Angular

Currently, I am encountering an issue where I cannot successfully store the specific data obtained from a Post request into a variable. How can I resolve this and ensure that only the desired data is stored? After making a Post request and receiving back ...

JavaScript Conversion from Binary to Decimal

This code is meant to convert a binary string ("100101") to its decimal equivalent. I am struggling to identify the issue causing it to not work properly. Any assistance would be greatly appreciated. function BinaryConverter(str) { var num=str.split("") ...

Converting a JSON PHP array into Javascript

How can I convert this PHP array named $data into JSON using json_encode? Whenever I try to do so in JavaScript by writing... var myJson = <?php echo json_encode($data) ?>; console.log(myJson); I encounter errors. I am curious about any restrictio ...

Send a property parameter to the Vue component

In my project using Vue and Laravel, I am trying to create a modal window with 2 tabs. The idea is to have two buttons, with each button linked to a specific tab that should open when clicked. These buttons are located in the blade template: <button ...

Uploading files to a server using Node.js without the need for additional frameworks

I am currently working on a basic file uploading website and I am utilizing the XmlHTTPRequest to handle file uploads. So far, I have dealt with this process only in the context of a server that was already set up for file uploading. Now, however, I need t ...

What are some ways to prevent having to constantly check for the existence of an object within another object when working

<template> <img :src="user.avatar_thumbnail"> <a :href="user.profile.link"/> </template> <script> export default { data: function () { user: {} }, ...

Reverting Changes Made with JQuery Append

I have a table where each cell contains a button. When the button is pressed, it adds text to the cell. I am looking for a way to remove this text from the cell when the same button is pressed again. It's important to note that this button appears mul ...