18
11

More than 5 years have passed since last update.

Angular FormGroupの setValue() と patchValue()

Last updated at Posted at 2018-10-06

何が違うの?

  • setValue()は全プロパティに対して、値をセットしているかをチェックします。
  • patchValue()はチェックしません。

どう言う事?

例えば下記のようなformをビルドしたとします。

form = new FormGroup({
    firstName: new FormControl(''),
    lastName: new FormControl(''),
    age: new FormControl(null),
    birthday: new FormControl(''),
});

このフォームに、サービスから取得した下記jsonデータをセットします。

customer: {
    firstName: 'Tanaka',
    lastName: 'Taro',
    birthday: '',
}

setValue の場合

customer.ageに値を付与していないと、console上にエラーが出ます。
ERROR内容: Must supply a value for form control at index: age.

form.setValue(customer); // Console error: Must supply a value for form control at index: age.

また、逆にjson側にformには存在しないプロパティが存在する場合もconsole上にエラーが出ます。

patchValue の場合

チェックはせず、存在するプロパティにだけ値を付与します。

form.patchValue(customer);

Angular内部のコードを確認

setValue()this._checkAllValuesPresent()throw new Error() をしているのを確認できます。

setValue(value: {[key: string]: any}, options: {onlySelf?: boolean, emitEvent?: boolean} = {}): void {
    this._checkAllValuesPresent(value);
    Object.keys(value).forEach(name => {
        this._throwIfControlMissing(name);
        this.controls[name].setValue(value[name], {onlySelf: true, emitEvent: options.emitEvent});
    });
    this.updateValueAndValidity(options);
}

/** @internal */
_checkAllValuesPresent(value: any): void {
    this._forEachChild((control: AbstractControl, name: string) => {
        if (value[name] === undefined) {
            throw new Error(`Must supply a value for form control with name: '${name}'.`);
        }
});
18
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
11