在Angular 7中初始化模板驱动表单 [英] Initializing Template Driven Form in Angular 7

查看:50
本文介绍了在Angular 7中初始化模板驱动表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要初始化表单上的某些表单字段,然后调用一个具有 if(this.form.valid)条件的函数.

ngOnInit 函数上的

我有一个API调用,该调用获取一些基本信息并将其填写在表单上:

  ngOnInit(){this.apiService.getInfo(this.user.id).subscribe(userInfo =>{this.formModel.fieldA = userInfo.A;this.formModel.fieldB = userInfo.B;this.formModel.fieldC = userInfo.C;this.doStuff();});} 

但是,当调用 this.doStuff()时,该表单无效,即使没有错误,并且单击提交"按钮似乎也可以强制验证并使其有效.

有没有一种方法可以手动触发表单的验证,以使 valid 变为true?

因此,您在 calc()中的 if :

  if(this.formExample&& this.formExample.valid) 

不是 truthy ,并且将不会计算 result ,因为该表单不是 valid .

因此,如果我们在调用 calc()之前等待一个滴答声,那应该可以解决您的问题:

  this.getInfo().subscribe(信息=>{this.params.field1 = info.field1;this.params.field2 = info.field2;//等待一会!setTimeout(()=> {this.calc();})}); 

STACKBLITZ

I'm looking to initialize certain form fields on a form and then call a function that has a if(this.form.valid) condition on it.

on the ngOnInit function I have an API call that gets some basic info and fills it on the form:

ngOnInit(){
    this.apiService.getInfo(this.user.id).subscribe(
        userInfo => {
            this.formModel.fieldA = userInfo.A; 
            this.formModel.fieldB = userInfo.B; 
            this.formModel.fieldC = userInfo.C; 
            this.doStuff();
        }
    );
}

However when calling this.doStuff() the form is invalid, even though there are no errors and clicking on the submit button seems to force the validation and causes it to be valid.

Is there a way I can manually trigger the form's validation so that valid becomes true?

Edit: Stackblitz.

解决方案

Angular template-driven forms are in fact asynchronous. This is more prominently shown when working with the NgForm directive in component, compared to reactive forms. If you were to put a debugger in your calc() function from the stackblitz:

You would see that in the calc function when called from OnInit shows that the form is not valid, nor does the form controls have any value:

So your if in calc():

if (this.formExample && this.formExample.valid)

is not truthy and result will not be computed since the form is not valid.

So if we wait a tick before calling calc() that should solve your issue:

this.getInfo().subscribe(
  info => {
    this.params.field1 = info.field1;
    this.params.field2 = info.field2;
    // wait a tick!
    setTimeout(() => {
      this.calc();
    })
  }
);

STACKBLITZ

这篇关于在Angular 7中初始化模板驱动表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆