【发布时间】:2018-04-12 10:05:07
【问题描述】:
在表单中,我有一个按钮,单击该按钮时,它应该提交表单并同时使用 routerLink 重定向到另一个组件。
这是我所拥有的:
<div class="container-fluid padding_elementos">
<div class="row">
<div class="card align-self-center">
<div class="card-body">
<form [formGroup]="forma" (ngSubmit)="saveChanges()">
<div class="form-group">
<label for="exampleInputEmail1">Correo Electrónico:</label>
<input type="email" class="form-control" placeholder="E-mail"
type="text"
formControlName="Correo">
</div>
<hr>
<div class="form-group">
<input type="password" class="form-control" placeholder="Nueva Contraseña" formControlName="Password">
<br>
<input type="password" class="form-control" placeholder="Repite Contraseña"
name="samePassword" formControlName="SamePassword">
</div>
<button type="submit" class="btn btn-primary btn-block" [routerLink]="['/login']">Guardar</button>
</form>
<br>
{{forma.valid}}
</div>
</div>
</div>
</div>
在我的 TS 文件中:
this.forma = new FormGroup({
'Correo': new FormControl('', Validators.required),
'Password': new FormControl('', Validators.required),
'SamePassword': new FormControl()
})
guardarCambios(){
console.log(this.forma.value)
this.forma.reset();}
提交效果很好,但是当我添加 routerLink 时,我收到以下消息:
表单提交因表单未连接而取消
它不提交任何东西。我做错了什么?
【问题讨论】:
-
为什么不在
saveChanges()方法中做重定向……表单提交后? -
您不应该同时尝试提交和重定向 - 提交需要时间将数据发送到服务器。如果出现错误会怎样?您需要停止重定向并显示错误。因此,您应该仅在更改成功保存后导航。因此在 saveChanges 方法中调用导航,不要在模板中使用 routerLink。
标签: javascript angular typescript