I have a scenario, Where I have 2 input fields name1,name2.I want to capture the name .But If the user enter name1,Then name2 should be empty.If user enter name2,Make the name1 empty.Always latest one have the value and the another one should be empty.
ngOnInit(): void {
this.form = this.fb.group({
inputName: ['', []],
pickerName: ['', []],
});
this.handleValueChange()
}
handleValueChange() {
this.form.controls['inputName'].valueChanges.subscribe((value) => {
this.form.controls['pickerName'].reset()
});
this.form.controls['pickerName'].valueChanges.subscribe((value) => {
this.form.controls['inputName'].reset()
});
}
This is the one I tried,But it generate a loop and getting error.How to handle this properly?
CodePudding user response:
The FormControl.reset
method accepts an options object with an emitEvent: boolean
property which you can set to avoid the inputs triggering each other programatically.
See: https://angular.io/api/forms/FormControl#reset
handleValueChange() {
this.form.controls['inputName'].valueChanges.subscribe((value) => {
this.form.controls['pickerName'].reset('', {emitEvent: false})
});
this.form.controls['pickerName'].valueChanges.subscribe((value) => {
this.form.controls['inputName'].reset('', {emitEvent: false})
});
}