如何在编辑时使用 table 行值填充 angular 模态表单?

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

我正在尝试获取特定行的用户详细信息,并在单击“编辑”按钮时将其填充到表单中,但我不确定该怎么做。我有一个方法,当我单击一行时,我将获得特定 ID 的更新表单,但该表单是空的。我如何获得一个填充了 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);
  }

在使用模式之前,我们可以改变创建表单的方式。我们将使用一个函数,该函数 return 一个 formGroup - 值为空或具有根据数据

的值
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.userConfigRecordForm=this.getForm() //and empty FormGroup
   //or
   this.userConfigRecordForm=this.getForm(data) //a FormGroup with "data"

好吧,我们有一个模式。如果我们使用material-angular模态,我们在打开模态

时将值传递给“数据”中的模态
  open(data)
  {
    const dialogRef = this.dialog.open(DialogOverviewExampleDialog, {
      width: '250px',
      data: {firstName: data.firstName, lastName: data.lastName,dob:data.dob}
    });
  }

所以,我们的组件可以像

  //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;
    }
  }

如果我们使用ng-bootstrap模态,给值的方式是在我们的组件中使用@Input,所以我们打开对话框

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

我们使用 @Input 来赋值,而不是使用 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;
    }
}

在这两种情况下我们都有一个函数open(data)。通常,当我们有一个 table 时,不需要再次询问 API 值,因为我们在“table”中有值。那么我们的 table 就像

<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>

好吧,有些时候只想将“id”传递给所选元素,所以我们有两个选择,

1.-我们打开的函数可以像

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.- 我们订阅了 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)
           ...
      }
  }