我正在构建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>
答案 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>
答案 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)
您只需在有效负载中设置提交按钮的类型,然后在后端代码中进行相应的操作即可。
//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>