angular2形式的多个提交按钮

时间:2016-11-05 20:49:06

标签: javascript angular angular2-forms

我正在构建angular2表单,我希望有多个按钮来提交表单,例如“保存”和“保存并关闭”。

我尝试使用简单按钮并对其执行点击操作,但我还是没有找到手动将表单标记为提交给强制表单验证。

<form #ticketForm="ngForm" novalidate>
    <input type="text" id="customerName" required
        name="customerName" [(ngModel)]="ticket.customerName"
        #customerName="ngModel">

    <div class="tj-form-input-errors"
        *ngIf="customerName.errors && (customerName.dirty ||
        customerName.touched || ticketForm.submitted)">

        <small [hidden]="!customerName.errors.required">
            Customer name is required
        </small>
    </div>

    <button type="button" (click)="save(ticketForm)">Save</button>
    <button type="button" (click)="saveAndClose(ticketForm)">Save and close</button>
</form>

3 个答案:

答案 0 :(得分:3)

为每个按钮分配不同的export class SignupComponent implements OnInit, OnDestroy { isLoading = false; private authSub: Subscription; usernameTaken = false; constructor(private authService: AuthService, private store: Store<AppState>) { } ngOnInit() { this.authSub = this.store .select(loading) .pipe( map(status => status) ) .subscribe(status => { this.isLoading = status; }); } onSignup(form: NgForm) { if (form.invalid) { return; } const signupData: SignupData = { email: form.value.email, username: form.value.username, password: form.value.password }; this.store.dispatch(AuthActions.trySignup({ payload: signupData })); } ngOnDestroy() { this.authSub.unsubscribe(); } } 。然后,您可以获得使用id触发提交的按钮的id。类似于以下内容:

在您的HTML中:

document.activeElement.id

然后输入您的打字稿:

<form #form="ngForm" (submit)="firstSave(form,$event)">
    ...
    <div class="form-group">
        <input type="submit" id="submit-1" value="Submit 1" class="btn btn-sm btn-primary"/>
        <input type="submit" id="submit-2" value="Submit 2" class="btn btn-sm btn-success"/>
    </div>
</form>

StackBlitz Here.

答案 1 :(得分:0)

您可以订阅表单更改,我认为这些更改将触发表单验证。

我这样做:

 this.physicalForm.valueChanges
   .map((value) => {
      return value;
   })
   .filter((value) => this.physicalForm.valid) 
   .subscribe((value) => {
      do what you need with the values here...
 });

然后在每个按钮的点击处理程序中,如果this.physicalForm.valid保存或保存并更新。

答案 2 :(得分:0)

我遇到了同样的情况。就我而言,我有2个提交“保存”,“保存并分配”

解决方案

您只需在有效负载中设置提交按钮的类型,然后在后端代码中进行相应的操作即可。

示例代码

//here formData is my payload for the API call eg: formData.name,formData.email

<button type="submit" class="btn btn-primary md" (click)="formData.save_type='save'">Save</button>
<button type="submit" class="btn btn-primary md" (click)="formData.save_type='allocate'">Save And Allocate</button>