在 Angular 11 中,由于嵌套表单的存在,如果想使用 Enter 键触发表单提交事件,可能会出现无法触发 NgSubmit 事件的情况。为了解决这个问题,我们可以在子表单中使用 FormControl 实例,并在表单中订阅该实例的 valueChanges 事件,然后在父组件中使用 ViewChild 和 NgForm 实例访问该子表单,并手动触发表单提交事件。
以下是示例代码:
在子组件中的 HTML 文件中:
在子组件中的 TypeScript 文件中:
import { Component, EventEmitter, Input, Output } from '@angular/core'; import { FormGroup, FormControl } from '@angular/forms';
@Component({ selector: 'child-component', templateUrl: './child-component.component.html', styleUrls: ['./child-component.component.css'] }) export class ChildComponent {
@Input() formGroup1: FormGroup;
@Output() onEnter: EventEmitter
ngOnInit() { this.formGroup1.addControl("input1", new FormControl("")); this.formGroup1.get("input1").valueChanges.subscribe(value => { if (value === "\n") { this.onEnter.emit(); } }); }
onKeyUp() { this.onEnter.emit(true); } }
在父组件中的 HTML 文件中:
在父组件中的 TypeScript 文件中:
import { Component, ViewChild } from '@angular/core'; import { NgForm, FormGroup, FormControl } from '@angular/forms';
@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] })