Search code examples
angularmodal-dialogcrudangular-reactive-formsmat-form-field

How to populate angular modal form with table row values when editing?


I'm trying to get the user details of a specific row and populate it into the form when I click the edit button but I'm not sure how to do it. I have a method when I click a row I will get the update form for a particular id but the form is empty..How do I get a form populated with firstName, lastName, dob?


export class AddUserComponent implements OnInit {
 
  userConfigRecordForm: FormGroup;
  reload: EventEmitter<string> = new EventEmitter();
  mode: FormMode = FormMode.NEW;
  formMode = FormMode;
  isOnViewMode = false;
  isExist: boolean = false;
  showProgressBar: boolean = false;
  showFormContent: boolean = true;
  num:number
  
  userRecord: User
 
  existMessage: string = "";
  

 


distric=[{
  "key":"Colombo",
  "value": "Colombo"
},
{
  "key":"Gampaha",
  "value":"Gampaha"
}

]

  
  constructor(private service:NewUserService,
    private snackBar: MatSnackBar,private formBuilder: FormBuilder,private dialogRef: MatDialogRef<AddUserComponent>, private dialog: MatDialog) { }

  ngOnInit() {
    this.userConfigRecordForm=new FormGroup({
      firstName: new FormControl(),
      lastName: new FormControl(),
      dob: new FormControl()
      
    });

    if (this.mode == FormMode.UPDATE) {
      this.service.getUserById(this.num).subscribe((data: any) => {
        this.userRecord = data;
        this.userConfigRecordForm.get("firstName").setValue(data.user.firstName);
        this.userConfigRecordForm.get("lastName").setValue(data.user.lastName);
        this.userConfigRecordForm.get("dob").setValue(data.user.dob);
        
        

        
      });
    }
  }

  



    
  

   save(options) {
   
    this.users.skills=this.selectedValue.toString();
    this.users.district=this.selectedDistrict;
   
 
    this.showProgressBar = true;
    this.showFormContent = false;
    this.isExist = false;
    if (this.mode == FormMode.NEW) {
 
      this.service.addUser({  // method to add user
        firstName: this.userConfigRecordForm.get('firstName').value,
        lastName: this.userConfigRecordForm.get('lastName').value,
        dob: moment(this.userConfigRecordForm.get('dob').value).format('YYYY-MM-DD'),
        
          
      }).subscribe((data: any) => {
        console.log(this.userConfigRecordForm.value);

        if (data.status === "userExist") {
          this.isExist = true;
          this.existMessage = "User is already used !";
          this.showProgressBar = false;
          this.showFormContent = true;
        } else {
          if (options == 'exit') {
            this.reload.emit();
            this.showProgressBar = false;
            this.openDialogCreateSucess();
            this.dialogRef.close();
          } else {
            this.showProgressBar = false;
            this.showFormContent = true;
            this.openDialogCreateSucess();
            this.num = data.user.num;
            this.mode = FormMode.UPDATE
          }
        }
      }
      ,
        error => {
          console.log(error);
          this.openDialogFailed();
          this.showProgressBar = false;
          this.showFormContent = true;
        });
    }
    else {
      this.service.updateUser(this.num,       //updates user through id
       
       
      
      {
        num:this.num,
        firstName: this.userConfigRecordForm.get('firstName').value, //trying to get it's value to the form
        lastName: this.userConfigRecordForm.get('lastName').value, 
        dob: moment(this.userConfigRecordForm.get('dob').value).format('YYYY-MM-DD'),
      
      }).subscribe((data: any) => {
        if (data.status === "userExist") {
          this.isExist = true;
          this.existMessage = "User is already used !";
          this.showProgressBar = false;
          this.showFormContent = true;
        } else {
          if (options == 'exit') {
            this.reload.emit();
            this.showProgressBar = false;
            this.openDialogUpdateSucess();
            this.dialogRef.close();
          } else {
            this.showProgressBar = false;
            this.showFormContent = true;
            this.openDialogUpdateSucess();
          }
        }
      },
        error => {
          console.log(error);
          this.openDialogFailed();
          this.showProgressBar = false;
          this.showFormContent = true;
        });

getUserById

public getUserById(num){
    return this.http.get("http://localhost:8080/dms-training-service/V1/example/users/id/"+ num);
  }

Solution

  • before use a modal, we can change the way to create the form. We are going to use a function that return a formGroup -with values empty or with values according a data

    getForm(data:any=null):FormGroup
    {
        data=data || {firstName:null,lastName:null,dob:null}
        return new FormGroup({
          firstName: new FormControl(data.firstName),
          lastName: new FormControl(data.lastName),
          dob: new FormControl(data.dob)
        });
    }
    

    This make that we can write

       this.userConfigRecordForm=this.getForm() //and empty FormGroup
       //or
       this.userConfigRecordForm=this.getForm(data) //a FormGroup with "data"
    

    Well, we has a modal. If we are using material-angular modal, we pass the value to the modal in "data" when open the modal

      open(data)
      {
        const dialogRef = this.dialog.open(DialogOverviewExampleDialog, {
          width: '250px',
          data: {firstName: data.firstName, lastName: data.lastName,dob:data.dob}
        });
      }
    

    So, our component can be like

      //if you use material angular modal
    
      export class AddUserComponent implements OnInit{
      constructor(
        public dialogRef: MatDialogRef<DialogOverviewExampleDialog>,
        @Inject(MAT_DIALOG_DATA) public data: DialogData) {}
      }
      ngOnInit()
      {
        if (this.data){
          this.userConfigRecordForm=this.getForm(this.data)
          this.mode=FormMode.UPDATE;
        }
        else{
          this.userConfigRecordForm=this.getForm()
          this.mode=FormMode.NEW;
        }
      }
    

    If we are using ng-bootstrap modal, the way to give value is using in our component a @Input, so we open the dialog like

      open(data) {
        const modalRef = this.modalService.open(NgbdModalContent);
        modalRef.componentInstance.data= {
              firstName: data.firstName, lastName: data.lastName,dob:data.dob
        }
      }
    

    And we use the @Inputto give value instead using ngOnInit

    @Input() set data(value)
    {
        if (value){
          this.userConfigRecordForm=this.getForm(value)
          this.mode=FormMode.UPDATE;
        }
        else{
          this.userConfigRecordForm=this.getForm()
          this.mode=FormMode.NEW;
        }
    }
    

    In both case we has a function open(data). In general, when we has a table it's not necesary ask to API the value again because we has in the "table" the values. Well our table is like

    <button (click)="open(null)">new</button>
    <table>
      <tr *ngIf="let element of myArrayWithData">
         <td>{{element.firstName}}</td>
             ....
         <td><button (click)="open(element)">Edit</button>
      </tr>
    </table>
    

    Well, some times only want to pass the "id" to the element selected, so we has two options,

    1.-Our funcions open can be like

    open(id){
        this.service.getUserById(id).subscribe(data=>{
           //if using material-angular
           const dialogRef = this.dialog.open(...}
           //if using ng-bootstrap
           const modalRef = this.modalService.open(...);
           modalRef.componentInstance.data= data;
        })
    }
    

    2.- we subscribe in the modalComponent

      //If using angular modal
      ngOnInit()
          {
            if (this.data.id){
             this.service.getUserById(id).subscribe(data=>{
                this.userConfigRecordForm=this.getForm(data)
                ...
            }
            else{
              this.userConfigRecordForm=this.getForm()
                ....
            }
          }
    
      //if using ng-bootstrap
      @Input() set data(value){
          if (value){
            this.service.getUserById(value).subscribe(data=>{
               this.userConfigRecordForm=this.getForm(value)
               ...
            }
          }
          else{
               this.userConfigRecordForm=this.getForm(value)
               ...
          }
      }