在Angular中,我们可以通过模板引用变量和NgForm指令访问表单元素和状态,以执行编程方式的表单提交并设置提交状态/类。
以下是示例代码:
HTML模板:
组件类:
import { Component, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponent {
@ViewChild('myForm') myForm: NgForm;
onSubmit() {
// 执行表单提交
this.myForm.onSubmit();
// 设置提交状态/类
this.myForm.form.markAsSubmitted();
this.myForm.form.addClass('submitted');
}
}
在上面的例子中,我们为表单指定了一个模板引用变量“myForm”,并在组件类中使用了@ViewChild装饰器来获取表单指令的实例。
在组件类中,我们定义了一个onSubmit方法,在该方法中通过调用“this.myForm.onSubmit()”来执行表单提交。然后我们使用“this.myForm.form.markAsSubmitted()”函数将表单状态标记为已提交,并使用“this.myForm.form.addClass('submitted')”函数添加一个名为‘submitted’的CSS类。
这样,我们就能够通过编程方式触发表单提交及设置其提交状态/类了。