无法使用内容之外的按钮提交表单(Ionic 4)
Unable to submit form with button outside of content (Ionic 4)
我使用模式来显示表单,在模式的 header 中我有一个 'Done' 按钮,我用它来提交表单。因为这个按钮在 header 标签中,而表单在内容标签中,所以我像这样使用 ngForm 来提交表单...
<ion-header>
<ion-toolbar>
<ion-buttons slot="start">
<ion-button color="primary" (click)="goBack()">Back</ion-button>
</ion-buttons>
<ion-buttons slot="end">
<ion-button color="primary" [disabled]="!profileForm.dirty || !profileForm.valid" (click)="goBack()">Save</ion-button>
</ion-buttons>
<ion-title>Profil</ion-title>
</ion-toolbar>
<ion-content color="medium" *ngIf="logged">
<form #profileForm="ngForm" name="profileForm" id="profileForm" novalidate>
export class ProfilePage implements OnInit {
@ViewChild('profileForm') form: NgForm;
预期行为
用户应该能够在表单外提交带有 ion-button 的表单。
您可以更改视图,使按钮处于以下形式:
<form>
<ion-header>
//submit button here
</ion-header>
<ion-content>
//form here
</ion-content>
</form>
或者在 'Save' 按钮的 (click)
处理程序中做任何你需要做的事情。
如果你使用反应式表单,你根本不会有这个问题;)我强烈建议你这样做!但这是您当前问题的解决方案。
因此,如果您没有 *ngIf
,您的代码实际上可以工作。结构指令范围模板引用变量只是结构指令中的内容,因为 angular 实际上为此创建了一个单独的模板。但是由于您正在使用 @ViewChild
来获取该模板引用,这就是您可以在代码中使用的内容。所以改变...
<ion-button [disabled]="!profileForm.dirty || !profileForm.valid" (click)="save()">
到...
<ion-button [disabled]="!form?.dirty || !form?.valid" (click)="save()">
我们需要使用安全导航运算符,因为在呈现模板时,我们还无法访问 form
变量。
我使用模式来显示表单,在模式的 header 中我有一个 'Done' 按钮,我用它来提交表单。因为这个按钮在 header 标签中,而表单在内容标签中,所以我像这样使用 ngForm 来提交表单...
<ion-header>
<ion-toolbar>
<ion-buttons slot="start">
<ion-button color="primary" (click)="goBack()">Back</ion-button>
</ion-buttons>
<ion-buttons slot="end">
<ion-button color="primary" [disabled]="!profileForm.dirty || !profileForm.valid" (click)="goBack()">Save</ion-button>
</ion-buttons>
<ion-title>Profil</ion-title>
</ion-toolbar>
<ion-content color="medium" *ngIf="logged">
<form #profileForm="ngForm" name="profileForm" id="profileForm" novalidate>
export class ProfilePage implements OnInit {
@ViewChild('profileForm') form: NgForm;
预期行为 用户应该能够在表单外提交带有 ion-button 的表单。
您可以更改视图,使按钮处于以下形式:
<form>
<ion-header>
//submit button here
</ion-header>
<ion-content>
//form here
</ion-content>
</form>
或者在 'Save' 按钮的 (click)
处理程序中做任何你需要做的事情。
如果你使用反应式表单,你根本不会有这个问题;)我强烈建议你这样做!但这是您当前问题的解决方案。
因此,如果您没有 *ngIf
,您的代码实际上可以工作。结构指令范围模板引用变量只是结构指令中的内容,因为 angular 实际上为此创建了一个单独的模板。但是由于您正在使用 @ViewChild
来获取该模板引用,这就是您可以在代码中使用的内容。所以改变...
<ion-button [disabled]="!profileForm.dirty || !profileForm.valid" (click)="save()">
到...
<ion-button [disabled]="!form?.dirty || !form?.valid" (click)="save()">
我们需要使用安全导航运算符,因为在呈现模板时,我们还无法访问 form
变量。