如何将数据从html表单元素传递到角度类

问题描述 投票:0回答:1

我正在使用angular 9,我需要将HTML表单数据绑定到angular类。我有以下角类:

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

而且我有以下HTML代码:

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

如何将HTML表单中的数据绑定到MyData角类?

html angular typescript angular-forms
1个回答
0
投票

为什么不为此使用Angular Form?

在您的组件中:

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

表单组跟踪其每个控件的状态和更改,因此,如果其中一个控件更改,则父控件也会发出新的状态或值更改。

在您的模板中:

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

更多信息here

© www.soinside.com 2019 - 2024. All rights reserved.