不使用 setValue 或 patchValue 更新反应式表单字段

Saj*_*jad 8 typescript angular angular-reactive-forms angular6

以下是我的一段代码,为了简洁起见,我简化了代码。

ngOnInit() {
    //intialize form fields 
    this.form = this.builder.group({
      name: '',
      age: '',
      location: '',
    });

    //Call to the service

    this.dataService.getDetails().subscribe(
      (data) => {
        this.dataArray = data;
        if (this.dataArray[this.count].status === 'OK') {
          let docs = {};
          this.someService.getDocs(this.dataArray[this.count].id).subscribe(
            (data) => {
              docs = data;
              console.log("docs: ", docs);
              this.setFormValues(docs);//set form values
            },
            (err) => {
              console.log(err);
              console.log('Something happened');
            }
          );
        }
      },
      (err) => {
        console.log(err);
        console.log('Something happened',err);
      }
    );
  }
Run Code Online (Sandbox Code Playgroud)

现在,setFormValues()我已经打印了字段的值及其工作正常,但接下来当我尝试form使用setValue或将值绑定到 时patchValue,它根本不会form使用从service.

这方面的更多代码

public setFormValues(doc: DocsDTO) {
    if (doc!= null) {
      console.log("setFormValues", doc);
      this.form.patchValue({
        name: doc.name == null ? '' : doc.name.text,
        age: doc.age == null ? '' : doc.age.text,
        location: doc.location == null ? '' : doc.location.text,
      })
    }
  }
Run Code Online (Sandbox Code Playgroud)

这是我的form样子

<form [formGroup]="form">
          <mat-card-content>
            <input placeholder="name" [formControl]="name" id="name"
              ngDefaultControl></input>
            <input placeholder="age" [formControl]="age" id="age" ngDefaultControl></input>
          </mat-card-content>
        </mat-card>
</form>
Run Code Online (Sandbox Code Playgroud)

注意:当我不使用FormBuilder和初始化表单字段FormControl并使用this.name.setValue()它设置表单值时,它工作正常。

我对 angular 很陌生,我不确定我在这里做错了什么。

nir*_*aft 4

除了您设置路径值的地方之外,这对我来说看起来不错:

\n

doc.name.text 对我来说看起来不正确。你应该试试

\n
this.form.patchValue({\n    name: !!doc.name ? doc.name : \'\',\n    age: !!doc.age ? doc.age: \'\',\n    location: !!doc.location ? doc.location : \'\',\n  })\n
Run Code Online (Sandbox Code Playgroud)\n

这将更新我们的 FormControl 实例,很简单!另外我认为我们不需要这里的条件设置:

\n
\n

由于在\nObject.keys 循环内进行 if 检查,set pathvalue 不会引发任何错误。有人可能会说它\xe2\x80\x99是一个安全的$apply,只是开玩笑。\n它\xe2\x80\x99将允许您设置存在的值,并且它将忽略\n当前迭代控件中不存在的值

\n
\n

另一方面,setValue 是一种更安全的 xe2x80x9d 做事方式。It\xe2\x80\x99ll 错误表示道具不存在。

\n

如果正确添加 formControlName,它将起作用:

\n
 <input placeholder="name" formControlName="name" id="name" ngDefaultControl>\n <input placeholder="age" formControlName="age" id="age" ngDefaultControl>\n
Run Code Online (Sandbox Code Playgroud)\n

看看我在这里为你做的 stackBlitz :

\n