问题描述
Angular-以编程方式提交表单.
Angular - Submit a form programmatically.
我在HTML上有一个表单组,我希望组件通过post方法中的email字段提交表单的操作.而不是使用常规的提交按钮.
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-以编程方式提交表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!