I have component CustomInputComponent
<div>
<input
#input="ngModel"
name="input"
[(ngModel)]="value"
(ngModelChange)="onInputChange()"
/>
</div>
@Component({
selector: 'app-custom-input',
templateUrl: './custom-input-component.html',
styleUrls: ['./custom-input-component.less'],
providers: [{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CustomInputComponent),
multi: true,
}],
})
export class CustomInputComponent implements ControlValueAccessor {
value= '';
onChange: (value: string) => void = () => {};
onTouched: () => void = () => {};
writeValue(value: string): void {
this.value = value;
}
registerOnChange(fn: (value: string) => void): void {
this.onChange = fn;
}
registerOnTouched(fn: () => void): void {
this.onTouched = fn;
}
onInputChange(): void {
this.onChange(this.value);
this.onTouched();
}
}
In other Component
<app-custom-input
#firstInput="ngModel"
[(ngModel)]="firstInputValue"
></app-custom-input>
<app-custom-input
#secondInput="ngModel"
[(ngModel)]="secondInputValue"
></app-custom-input>
<div>
First touched: {{firstInput.touched}}
<br/>
Second touched: {{secondInput.touched}}
</div>
When I enter one of the two app-custom-inputs, the firstInput and secondInput will change to the data of the newly entered input. But with firstInputValue and secondInputValue, the correct value of the input word is displayed
I want to enter data into firstInput, firstInput.touched must be true but secondInput must still be false
New contributor
Hồng Lĩnh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.