问题描述
Angular - 以编程方式提交表单.
Angular - Submit a form programmatically.
我在 HTML 上有一个表单组,我希望组件通过 post 方法中的电子邮件字段提交表单的操作.而不是使用普通的提交按钮.
I have a form group on the HTML and I want the component to submit the form's action with an email field in a post method. Instead of using a normal submit button.
下面的 testMethod 被另一个按钮调用.在这种方法中,我想发布testForm.它必须以老派的方式发布,因为它需要采取行动.
Below's testMethod gets called from another button. In this method, I want to post the testForm. It has to be posted old school way as it needs an action.
这是我的 HTML:
<form
[formGroup]="testGroup"
[action]='actionLink'
method='POST'
#testForm>
<input name='Email' type='hidden' [value]='currentUserEmail'>
</form>
这是我的组件 TS 文件尝试:
@ViewChild('testForm') testFormElement;
public currentUserEmail: string = '';
public testGroup = this.formBuilder.group({
Email: ''
});
public testMethod(): void {
// Below: This currently doesnt seem to do anything.
this.testFormElement.ngSubmit.emit();
}
推荐答案
您可以在表单中使用 ngNoForm
来移除 ngForm
处理并添加普通的 javascript 处理程序.
You can use ngNoForm
with your form to remove ngForm
handling and to add plain javascript handler.
您可以按如下方式使用您的代码:
you can use your code as follows:
HTML 文件.
<form ngNoForm
[formGroup]="testGroup"
[action]='actionLink'
method='POST'
#testForm>
<input name='Email' type='hidden' [value]='currentUserEmail'>
</form>
Ts 文件.
@ViewChild('testForm') testFormElement;
public currentUserEmail: string = '';
public testGroup = this.formBuilder.group({
Email: ''
});
constructor(formBuilder: FormBuilder) {
}
public testMethod(): void {
this.testFormElement.nativeElement.submit();
}
这篇关于Angular - 以编程方式提交表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!