代码之家  ›  专栏  ›  技术社区  ›  Devmix

如何在窗体上设置多个值?

  •  3
  • Devmix  · 技术社区  · 6 年前

    我知道如果我想在一个字段上设置一个值,我可以使用

    设定值

    补丁值

    但是,我面临着这个问题,我不想在每个字段上设置值。 逐一地 .

    这是我的表格代码:

    registrationForm = this._fb.group({
     firstName: ['', Validators.required],
     lastName: [''],
     age: [''],
     country: ['', Validators.required],
     hobby: [''],
     sport: [''],
     status: [''],
     country: ['', Validators.required],
     ...
     ...
    });
    

    我有一个叫 它具有所有这些属性,所以为了设置值,我要这样做( 它工作 但是我想找一个 更好 这样做的方式:

    registrationForm = this._fb.group({
     firstName: [this.person.firstName, Validators.required],
     lastName: [this.person.lastName],
     age: [this.person.age],
     country: [this.person.country, Validators.required],
     hobby: [this.person.hobby],
     sport: [this.person.sport],
     status: [this.person.status],
     country: [this.person.country, Validators.required],
     ...
     ...
    });
    

    我想的另一种方式是从Person对象创建一个对象,这样我就可以使用setValue或patchValue。比如:

     Object
     .keys(dataObject)
     .map((key) => {
     return { firstName: firstName, lastName: lastName, age: age ...}
     });
    

    有人能给我指出正确的方向吗?提前多谢!

    1 回复  |  直到 6 年前
        1
  •  0
  •   AT82    6 年前

    如果你知道 person 对象与窗体的属性匹配,您只需使用 setValue 对于整个窗体 :

    this.myFormGroup.setValue(this.person);
    

    DEMO


    编辑:如果您的 对象,不在窗体中的属性,然后只使用 patchValue() 而是采用与表单匹配的属性:

    this.myFormGroup.patchValue(this.person);
    

    DEMO

    推荐文章