Search code examples
angulartypescripttwitter-bootstrapmdbootstrap

Input form fields are cannot be updated in Angular app?


I'm creating simple web page which has modal for creating new object Partner and sending it to server. And several input fields to display newly created data. I am using Angualr10 and mdbootstrap for the components.

I have a button and a form with only input fields, which are disabled and they serve the purpose of just representing created Partner.

After landing on page, user can click on button to open modal to enter new data about Partner. After hitting "save", I successfully sent Partner object to the server and get it back with an id. After that, currentPartner is initialized and not null.

enter image description here

My problem is that I'm not able to update input fields using currentPartner object. How do I know that currentPartner is not null? Well, if I click on any of the input fields (after sending data to server), that filed is updated with data I previously entered in the modal.

enter image description here

Here is the code:

    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>

What else is the problem? I don't know "Angular" way of saying: "If currentPartner is null display placeholder value, else display currentPartner's value"?


Solution

  • You are super close, you can use ng-template and ng-container to toggle the UI based on currentPartner

    <ng-container *ngIf="currentPartner; else placeholderPartner">
      <!-- shows when currentPartner is defined -->
    </ng-container>
    
    <ng-template #placeholderPartner>
      <!-- shows when currentPartner is null/undefined -->
    </ng-template>