Home > Net >  Exclude a button from onBlur from input (Angular)
Exclude a button from onBlur from input (Angular)

Time:07-05

Good morning, thank you in advance for your help. I have an input that has some buttons positioned with absolute position, I want to make it so that when you blur the input it cancels the edit mode and makes you blur the input, the problem is that if I click on the check icon I want it not to be executed the blur of the input, because I want that when you do check it calls another function, my problem is that when I want to click on the check button, the input detects its blur and cancels the edition

My HTML:

<div >
  <input [(ngModel)]="this.value" #inputEditable [title]="this.isEditing ? '' : 'Este campo es editable'"
    (focus)="this.onFocus($event)" (keyup.enter)="this.onInputEditableChange(inputEditable)"
    (keyup.escape)="this.onCancel(inputEditable)" (blur)="this.onCancel(inputEditable)"  />
  <fa-icon *ngIf="this.isEditing" (click)="this.onCancel(inputEditable)" 
    [icon]="this.iconService.getIcon('faTimes')">
  </fa-icon>
  <fa-icon *ngIf="this.isEditing" (click)="this.onInputEditableChange(inputEditable);" 
    [icon]="this.iconService.getIcon('faCheck')">
  </fa-icon>
</div>

My TS:

  @Input() fieldName: string = 'Titulo';
  @Input() value: string = 'Hola';
  isEditing = false;
  oldValue: string;

  constructor(public iconService: IconService, private toastNotificationService: ToastNotificationService) { }

  ngOnInit(): void {
  }

  onFocus(event: any) {
    this.oldValue = event.target.value;
    this.isEditing = true;
  }

  onInputEditableChange(inputDirective: HTMLInputElement) {
    let newValue = this.value;
    if (newValue != this.oldValue) {
      this.toastNotificationService.success(`Has modificado el valor del campo "${this.fieldName}"`);
    }
    this.onBlur(inputDirective);
  }

  onCancel(inputDirective: HTMLInputElement) {
    this.toastNotificationService.warning(`Has cancelado la edición del campo "${this.fieldName}"`);
    this.value = this.oldValue;
    this.onBlur(inputDirective);
  }

  onBlur(inputDirective: HTMLInputElement) {
    this.isEditing = false;
    inputDirective.blur();
  }

My CSS:

.input {
  background: transparent;
  border: none;
  font-size: 0.9rem;
  font-weight: 700;
}

.input:focus-visible {
  border: none;
  outline: none;
}

.cancel-edit-icon {
  position: absolute;
  top: 0;
  right: 1.4rem;
  font-size: 1.1rem;
  cursor: pointer;
}

.confirm-edit-icon {
  position: absolute;
  top: 0;
  right: 0rem;
  font-size: 1.1rem;
  cursor: pointer;
}

Thanks for the help! :)

CodePudding user response:

Try adding a timeout to your blur fonction so it takes some time before blur, and your code detect the checkbox if it's checked/unchecked

  onBlur(inputDirective: HTMLInputElement) {
    setTimeout(() => {
     this.isEditing = false;
     inputDirective.blur();
    }, 1000);
  }
  • Related