需确认表单已包含在form标签内,并且button的type属性设置为submit。同时,在模板驱动表单中或响应式表单中都需要包含FormsModule以及ReactiveFormsModule模块。 示例代码如下:
// component.ts import { Component } from '@angular/core'; import { NgForm } from '@angular/forms';
@Component({ selector: 'app-form', templateUrl: './form.component.html', styleUrls: ['./form.component.css'] }) export class FormComponent { onSubmit(form: NgForm) { console.log(form.value); } }