FormControlなどにあるsetValue()
とかpatchValue()
とかreset()
にはoptionにはonlySelf
を指定できます。1
公式の説明にはこうあります。
onlySelf: When true, each change only affects this control, and not its parent. Default is false.2
説明の通りなのですがonlySelf
は、
「true
を指定した場合、controlの変更が親に影響しない」です。
因みにデフォルトがfalse
です。
これの動きについて実際に動かして確認したいと思います。
例で確認する
良くあるformを考えます。
formGroup: FormGroup;
constructor(
private formBuilder: FormBuilder,
)
ngOnInit() {
this.formGroup = this.formBuilder.group({
control: ['hoge', [Validators.required]],
});
}
falseの場合
更新するときはこうですね。
this.formGroup.get('control').setValue('hogehoge', {onlySelf: false});
this.formGroup.get('control').value; // hogehoge
this.formGroup.value; // {control: "hogehoge"}
すると、、
controlを更新したら親にも影響がありました!
trueの場合
this.formGroup.get('control').setValue('hogehoge', {onlySelf: true});
this.formGroup.get('control').value; // hogehoge
this.formGroup.value; // {control: "hoge"}
こちらは、、
controlを更新しても親には影響がありませんね!
完全に理解しました!
別の例
値だけではなくバリデーションにも影響してきます。
確認してみましょう。
falseの場合
this.formGroup.get('control').setValue('', {onlySelf: false});
this.formGroup.get('control').valid; // false
this.formGroup.valid; // false
必須チェックバリデーションが親にも影響してますね!
trueの場合
this.formGroup.get('control').setValue('', {onlySelf: true});
this.formGroup.get('control').valid; // false
this.formGroup.valid; // true
こちらは予想通り、影響していません!
まとめ
実際に見てみると一目瞭然ですね!
これでonlySelf
について確認できたかと思います。