Is it possible to update input form fields in an Angular application?

I am currently designing a straightforward web page featuring a modal for creating a new object named Partner and sending it to the server. The page also includes multiple input fields to showcase the newly created data. In this project, I am utilizing Angualr10 along with mdbootstrap components.

The setup consists of a button and a form containing only disabled input fields. These fields serve the purpose of displaying information about the created Partner.

Upon visiting the page, users can click on the button to open a modal where they can input new data related to the Partner. Upon clicking "save," the Partner object is successfully sent to the server and retrieved back with an id. As a result, the variable currentPartner is initialized and not null.

https://i.sstatic.net/wIIz8.png

The challenge arises when attempting to update the input fields using the currentPartner object. How do I ensure that currentPartner is not null? Well, if I click on any of the input fields (after sending data to the server), that particular field gets updated with the data previously entered in the modal.

https://i.sstatic.net/YEDQE.png

Below is the code snippet:

    currentPartner : Partner; //declare partner

      savePartnerAndCloseModal(modal : any){
           modal.hide()
           var partner = <Partner>{}
           partner.name = this.name.value;
           partner.phone = this.phone.value;
           partner.taxNumber = this.taxNo.value;
           partner.email =  this.phone.value;
           partner.address = this.address.value;
    
           this.partnerService.addPartner(partner).subscribe(data =>{
             this.currentPartner = data //Partner from server with id
             this.partners.push(data) //some list with other Partners
           });

  }
      <form class="text-center border border-light p-5" >
      
        <p class="h4 mb-4">Business Partner</p>
      
        <!-- Name -->
        <div [ngModel]="currentPartner" *ngIf="currentPartner; else elseBlock">
          <input type="text"    mdbInput disabled
          class="form-control mb-4" [value]="currentPartner.name"  >
        </div>
        <ng-template #elseBlock>
          <input type="text" disabled   mdbInput
          class="form-control mb-4" placeholder="Name" >
        </ng-template>
        
                 
        <!-- Address -->
        <input type="text" disabled mdbInput
          class="form-control mb-4" placeholder="Address">
       
        //other properties (inputs) for partner
      </form>

Additonally, I need guidance on how to handle the situation in Angular; specifically, how can I show placeholder values if currentPartner is null, and display currentPartner's value otherwise?

Answer №1

Try using ng-template along with ng-container to switch the user interface depending on the value of currentPartner

<ng-container *ngIf="currentPartner; else placeholderPartner">
  <!-- display when currentPartner is available -->
</ng-container>

<ng-template #placeholderPartner>
  <!-- display when currentPartner is null or undefined -->
</ng-template>

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 creating a recursive string literal type in Typescript

I need to create a type that represents a series of numbers separated by ':' within a string. For example: '39:4893:30423', '232', '32:39' This is what I attempted: type N = `${number}` | '' type NL = `${ ...

Adjust the height of the following column to match the responsive height of the initial column

Those who have marked it as duplicate, I want to clarify that my question is not about making Bootstrap columns all the same height. Instead, I am focusing on responsive images while maintaining their aspect ratio, which is a different issue from simply en ...

unable to call a function within Angular

To create a dynamic menu, I am utilizing primeng's menu panel. Firstly, I declare my item variable: items: MenuItem[]=[]; I have two JavaScript objects to incorporate into the menu, namely groupsItem and ejsItem. Here is their structure: groupsI ...

Having trouble importing the UpgradeModule from @angularupgradestatic in Angular version 2.2.1

I am in the process of updating my AngularJS (ng1) application to Angular 2 (ng2). My Angular version is 2.2.1. Upon importing UpgradeModule from @angular\upgrade\static, I encountered the following exceptions: Uncaught SyntaxError: Unexpected ...

Strategies for effectively conveying jQuery and Angular

I have integrated jQuery DataTable into my code. I am facing an issue with the dataTables_scrollBody class which requires me to add a custom scroll bar. This is necessary because on Linux, the touch screen functionality in Chrome is not working effectively ...

Exploring the benefits of utilizing TypeScript's async await feature within the Node

I've encountered a challenge trying to accomplish the following tasks simultaneously: Developing in Node.js Coding in TypeScript Implementing async await Facilitating debugging Background: In my TypeScript-based Node.js project, I am incorporating ...

Utilizing Array.every to refine a union of array types, narrowing down the options

I need to narrow down the type of a variable that is a union of different array types in order to run specific code for each type. I attempted to use Array.every along with a custom type guard, but encountered an error in TypeScript stating "This expressio ...

What is the best way to structure a nested object model in Angular?

Issue occurred when trying to assign the this.model.teamMembersDto.roleDto to teamMembersDto. The error message states that the property roleDto does not exist on type TeamMembersDropdownDto[], even though it is nested under teamMembersDto. If you look at ...

What is the best way to mark a specific photo as a favorite in an array of Photo objects?

I am working with a basic array of photo categories that follows this structure: [ { category: 1001, photos: [ { id: 100101, url: 'url.com/100101', favorite: false}, { id: 100102, url: 'url.com/100102', favorite: ...

Implementing Angular 4 to fetch information from a JSON file

As a beginner in Angular, my current task involves loading data from a JSON file upon click, which I have successfully achieved so far. However, I am facing an issue where I'm unable to load the first JSON object before clicking, meaning that I want ...

"Upon submitting a form in React JS, the components will automatically trigger a

Within my application, there is a Mobx storage in conjunction with a modal window component. The form within the modal window allows me to collect all the properties and push them into an array named 'cart' within the storage as an object. Take a ...

The formio onchange event may result in an undefined object

Encountering an issue here: Error: src/app/app.component.html:1:30 - error TS2532: Object is possibly 'undefined'. 1 <form-builder [form]="form" (change)="onChange($event)"></form-builder> while working on my for ...

Issue with displaying MP4 movies in Angular

I'm trying to display an mp4 video in Angular 9: <video controls (click)="toggleVideo()" preload="none" *ngIf="post.moviePath != null" #videoPlayer> <source [src]="getMovieSanitazePath(post.moviePath ...

Exploring the fruitful synergy of Node.js, Mongoose and MongoDB in Typescript for powerful MapReduce operations using the emit() function

Currently, I am experimenting with a side project using the MEAN stack and Typescript. I have encountered an issue where Typescript is not recognizing the typings for the emit() and Array.sum() methods. See my code snippet below... let options: mongoose. ...

Stripe detects that no signatures match the expected payload

Currently working on setting up a checkout session using Stripe that triggers my webhook upon successful completion. The issue I am facing is an error message stating "error: No signatures found matching the expected signature for payload. Are you passing ...

"Exploring the World of Websockets Using Ionic 3 and Angular

How can I successfully implement a Websocket in Ionic 3 and Angular 4? I attempted to use the socket.io-client package, but when I try to connect the websocket using the following code: this.socket = io(this.urls.websocket, {transports: ['websocket& ...

Combining arrays of objects sharing a common key yet varying in structure

Currently, I am facing a challenge while working on this problem using Typescript. It has been quite some time since I started working on it and I am hoping that the helpful community at StackOverflow could provide assistance :) The scenario involves two ...

Integrating meta tags into Angular Universal through subscription

I am facing challenges with dynamically setting meta tags in my Angular application. I am able to set the tags in the ngOnInit method without any issues, but when I try to use a Subscription, the addTag method doesn't work as expected. export class Ap ...

I need help understanding how to access the map[#var] when using *ngFor="var of list"

If I define a local variable using *ngFor in my template, how can I utilize it as a key to access a map? The template code shown below leads to a Parser Error: Unexpected token # at column 12 in ... <li *ngFor="#item of my_list"> <div [class]="m ...

Using Regular Expressions as an Alternative to Conditionals

My knowledge of RegEx is limited, but I'm trying to make the following expression work with Javascript/Typescript: /^({)?(?(1)|(\()?)[0-9A-F]{8}(-)?([0-9A-F]{4}(?(3)-)){3}[0-9A-F]{12}(?(1)}|(?(2)\)))$/i This RegEx is used to check if a str ...