0

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?

1
  • 2
    angular.io/guide/forms Commented Apr 28, 2020 at 11:40

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.