Ang*_*arM 13 angular2-forms angular angular5
Angular - 以编程方式提交表单.
我在HTML上有一个表单组,我希望组件使用post方法中的电子邮件字段提交表单的操作.而不是使用正常的提交按钮.
下面的testMethod从另一个按钮调用.在这个方法中,我想发布testForm.它必须以旧学校的方式发布,因为它需要一个动作.
这是我的HTML:
<form
[formGroup]="testGroup"
[action]='actionLink'
method='POST'
#testForm>
<input name='Email' type='hidden' [value]='currentUserEmail'>
</form>
Run Code Online (Sandbox Code Playgroud)
这是我的Component 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();
}
Run Code Online (Sandbox Code Playgroud)
我认为您应该在代码中使用 ngForm。所以,重写你的代码如下:
<form
[formGroup]="testGroup"
[action]='actionLink'
method='POST'
#testForm="ngForm" (ngSubmit)="testForm.form.valid ? yourSaveMethod() :showValidatinErrors()">
<input name='Email' type='hidden' [value]='currentUserEmail'>
</form>
Run Code Online (Sandbox Code Playgroud)
并在您的 ts 文件中:
@ViewChild('testForm') testFormElement: NgForm;
public testMethod(): void {
// Below: This works for me.
this.testFormElement.ngSubmit.emit();
}
public yourSaveMethod(): void {
// post your model here.
}
Run Code Online (Sandbox Code Playgroud)
您可以在表单中使用ngNoForm来删除ngForm处理并添加纯JavaScript处理程序。
您可以按以下方式使用代码:
HTML文件。
<form ngNoForm
[formGroup]="testGroup"
[action]='actionLink'
method='POST'
#testForm>
<input name='Email' type='hidden' [value]='currentUserEmail'>
</form>
Run Code Online (Sandbox Code Playgroud)
Ts文件。
@ViewChild('testForm') testFormElement;
public currentUserEmail: string = '';
public testGroup = this.formBuilder.group({
Email: ''
});
public testMethod(): void {
this.testFormElement.nativeElement.submit();
}
Run Code Online (Sandbox Code Playgroud)
import { Component, ViewChild } from '@angular/core';
@Component({
template: `
<form #testForm>
<input name='Email' type='hidden'>
</form>
`
})
class MyComponent {
@ViewChild('testForm') testFormEl;
testMethod() {
this.testFormEl.nativeElement.submit()
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13065 次 |
| 最近记录: |