我正在使用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
角度类?
答案 0 :(得分:1)
为什么不为此使用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