Search code examples
angular5angular4-forms

Same template driven form for creating and editing data Angular4 example


I want to edit form with existing object values. I can't do it because I haven't idea how to do that? I tried different technique two-way data binding but I not found any solution


Solution

  • Reactive Forms

    You can you use reactive forms. First, import Forms and Reactive Forms to your app.module.ts:

    imports: [
         ...
         FormsModule,
         ReactiveFormsModule,
         ...
    ]
    

    then in your component, use FormBuilder like this:

    constructor(private fb: FormBuilder){
      this.initForm(firstname, lastName);
    }
    
    myForm: FormGroup;
    
    initForm(firstname, lastName) {
           this.myForm = this.fb.group({
                 first_name: [firstname, Validators.required],
                 last_name: [lastName, Validators.required],
                 nick_name: [null, Validators.required]
       });
    }
    

    Then in your template:

    <form [formGroup]="myForm">
         <input type="text" formControlName='first_name' />
         <input type="text" formControlName='last_name' />
         <input type="text" formControlName='nick_name' />
    </form>
    

    A useful tip here, is to print your form Values to see their changes: to this for debugging purpose, add this to your template:

    <pre>{{myForm.value | json}}</pre>