Search code examples
htmlangulartypescriptangular-forms

How to pass data from html form elements to the angular class


I'm using angular 9 and I need to bind HTML forms data to the angular class.
I have the following angular class:

export interface MyData {
    field1: string,
    textArea1: string,
    textArea2: string
}

and I have the following HTML code:

<div class="modal-body">
        <label>Field1</label>
        <input type="text" class="form-control" aria-label="Process id"/>
        <label>TextArea1</label>
        <textarea class="form-control" aria-label="With textarea"></textarea>
        <label>TextArea2</label>
        <textarea class="form-control" aria-label="With textarea"></textarea>
      </div>

How can I bind data from the HTML form to the MyData angular class?


Solution

  • Why don't you use Angular Form for that ?

    In your component:

    import { Component } from '@angular/core';
    import { FormGroup, FormControl } from '@angular/forms';
    
    @Component({
     selector: 'app-your-component-selector',
     templateUrl: './your-component.component.html',
     styleUrls: ['./your-component.component.css']
    })
    export class YourComponent {
     /** new form group instance */
     form: FormGroup;
    
     constructor() {}
    
     ngOnInit(): void {
         this.initForm();
     }
    
     initForm(): void {
        /** field1, textArea1, textArea2 are form control instances */
        this.form = new FormGroup({
            field1: new FormControl(''),
            textArea1: new FormControl(''),
            textArea2: new FormControl(''),
        });
     }
    
     onSubmit(): void {
       // code here after submit
       console.info(this.form.value);
     }
    }
    

    A form group tracks the status and changes for each of its controls, so if one of the controls changes, the parent control also emits a new status or value change.

    In your template:

    <div class="modal-body">
      <form [formGroup]="form" (ngSubmit)="onSubmit()">
        <label>Field1</label>
        <input type="text" class="form-control" formControlName="field1" aria-label="Process id"/>
    
        <label>TextArea1</label>
        <textarea class="form-control" formControlName="textArea1" aria-label="With textarea"></textarea>
    
        <label>TextArea2</label>
        <textarea class="form-control" formControlName="textArea2" aria-label="With textarea"></textarea>
      </form>
    </div>
    

    More information here