【问题标题】:Submission Canceled with Angular Forms使用 Angular 表单取消提交
【发布时间】: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


【解决方案1】:

您已绑定到表单的提交事件

(ngSubmit)="saveChanges()"

既然你这样做了,你不应该从你的按钮重定向,而是从你的组件

向路由器添加依赖项

constructor(private router: Router) {}

在你的函数中

saveChanges() {
  // ... Do what you have to do then
  this.router.navigate(['/login']);
}

【讨论】:

  • 是的,这就是我在评论中提到的;]。
  • 我很高兴你的意思是这样,但是评论中的 15 个字不值得用代码示例给出完整的答案;)
  • 谢谢你们俩
猜你喜欢
  • 2015-11-20
  • 2015-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多