Skip to content

Instantly share code, notes, and snippets.

@rakia
Created July 21, 2024 18:44
Show Gist options
  • Save rakia/0aaf56267d6d9681b69f0c18d543ca1f to your computer and use it in GitHub Desktop.
Save rakia/0aaf56267d6d9681b69f0c18d543ca1f to your computer and use it in GitHub Desktop.
Angular: Logic to show real-time feedback to users when they type a name that already exists in the system
@Component({
selector: 'app-create-custom-field',
templateUrl: './create-custom-field.component.html',
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CreateCustomFieldComponent implements OnInit {
private readonly destroyRef = inject(DestroyRef);
@Input() nameAlreadyExists: boolean | null = false;
@Output() checkIfNameExists = new EventEmitter<string>();
ngOnInit(): void {
this.updateForm();
this.notifyParentComponentWhenNameChanges();
}
private notifyParentComponentWhenNameChanges(): void {
this.form
?.get('name')
?.valueChanges.pipe(
takeUntilDestroyed(this.destroyRef),
debounceTime(300), // debounce user input
distinctUntilChanged()
)
.subscribe((name) => {
if (name) {
this.checkIfNameExists.emit(name);
}
});
}
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment