Populating/patching values of angular reactive forms

亡梦爱人 提交于 2019-12-25 00:26:45

问题


I'm curently working on crud application using angular 4, I'm wondering, how can I populate my reactive form with the data that's been parsed in the same row with the button that opens up the form, form is inside ngx-bootstrap modal and it should be the same one I have on the other button for adding new item/object?

Here's the code, I hope I can present my problem to you properly...

I should noted that I have a working form for adding new employee, and want to use same one but want to populate the form with the values of the object I click on/row where the edit button is... (sorry for the lack of better explanation) So I have a class of my object

        export class employee {
        UserId: string;
        FirstName: string;
        LastName: string;
        Email: string;
        }

In my app.component.ts I have

     ngOnInit() {
    // populates table with current users in database onInit
    this.LoadAllEmployees();


    this.form = this.formBuilder.group({
        FirstName: [null, [Validators.required, Validators.minLength(2)]],
        LastName: [null, Validators.required],
        Email: [null, [Validators.required, Validators.email]],

    });

       }

    onSubmit() {
    if (this.form.valid) {
        console.log("Form Submitted!", this.form.value);
        this.form.reset();
        this.modalRef.hide();

    }
    else {
        this.validateAllFormFields(this.form)
    }
     }

    Save(myForm: NgForm) {
    this.GetDemoObject(myForm);
    this.AddEmployee(this.Demoemployee);
    }

    GetDemoObject(myForm: NgForm): employee {
    this.Demoemployee = new employee;
    this.Demoemployee.FirstName = myForm.value.FirstName;
    this.Demoemployee.LastName = myForm.value.LastName;
    this.Demoemployee.Email = myForm.value.Email;
            return this.Demoemployee;
     }

In my app.component.html there's a table and ngx-bootstrap call

      <table style="width:100%" class="table table-striped" 
     id="billing_history_table">
     <thead class="head">
        <tr>
            <th>Employee Name</th>
            <th>Mail</th>
            <th></th>

        </tr>
        </thead>
       <tbody>
        <tr *ngFor="let e of employeelist; let i = index ">
            <td>{{e.firstName + '&nbsp;' +e.lastName}}</td>
            <td>{{e.positionId}}</td>
            <td>{{e.email}}</td>
           <td><a (click)="openModal(template)"><span class="glyphicon 
             glyphicon-edit"></span></a></td>
           </tr>
           </tbody>
           </table>
       </div>

      <ng-template #template>

       <div class="modal-content">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-
     label="Close" (click)="modalRef.hide()"><span aria-hidden="true">&times;
    </span></button>
        <h4 class="modal-title" id="myModalLabel">Add new user</h4>
    </div>
    <div class="modal-body">
        <form class="form-horizontal" [formGroup]="form" #myForm="ngForm" 
   (ngSubmit)="onSubmit(myForm.value)">


            <div class="form-group" [ngClass]="displayFieldCss('FirstName')">
                <label for="FirstName" class="control-label required">First 
      name</label>
                <input type="text" id="FirstName" class="form-control" 
       formControlName="FirstName">

                <app-field-error-display 
      [displayError]="isFieldValid('FirstName')"
                                         errorMsg="First name is not valid!">
                </app-field-error-display>
            </div>

            <div class="form-group" [ngClass]="displayFieldCss('LastName')">
                <label for="LastName" class="control-label required">Last 
        name</label>
                <input type="text" id="LastName" class="form-control" 
       formControlName="LastName">
                <app-field-error-display 
        [displayError]="isFieldValid('LastName')"
                                         errorMsg="Last name is not valid!">
                </app-field-error-display>
            </div>

            <div class="form-group" [ngClass]="displayFieldCss('Email')">
                <label for="Email" class="control-label 
        required">Email</label>
                <input type="text" id="Email" class="form-control" 
       formControlName="Email">
                <app-field-error-display 
        [displayError]="isFieldValid('Email')"
                                         errorMsg="Email is not valid!">
                </app-field-error-display>
            </div>



            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-
         dismiss="modal" (click)="modalRef.hide()">Close</button>
                <button type="submit"
                        class="btn btn-primary" (click)="Save(myForm)">
                    Submit
                </button>

            </div>

        </form>
    </div>

       </div>
     </ng-template>

Can anyone give me some directions, some example of similar thing or any advice, please...


回答1:


Set up the values of a form is basically in the same way as you are creating the form. In your code when you declare the form field FirstName: [null, [Validators.required, Validators.minLength(2)]],

actually the first parameter that you are passing is the initial value of the form field (null). you can use that approach, receiving the values of your from from the parent component and creating the form with default values...

Usually what I do is pass the parameter that identify my object (the id of the object) through the route, then I fetch the real object from the backend or the store and populate the form based on the parameters that I receive

I use the method setValue from fromControl to set up the value to the form field

this.userForm.get("name").setValue(user.name)

let me know if you need more info

greetings



来源:https://stackoverflow.com/questions/49057998/populating-patching-values-of-angular-reactive-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!