0

I've created a text input like below:

<input 
    id="tenancyName" 
    #tenancyName="ngModel" 
    class="register__form__control" 
    autoFocus 
    type="text" 
    placeholder="Business Name" 
    [(ngModel)]="model.tenancyName"
    name="tenancyName" 
    required 
    maxlength="64" />

and after my input, I have a div which is a warning that the business name they have entered is already taken.

<div [class.taken]="taken === true" class="register__warning">
    <p>Sorry, Business Name is already taken</p>
</div>

then in my component.ts

import ... from ...

import * as _ from 'lodash';

@component...
export class...

  taken: boolean;

  ngOnInt() {
    const businessInput = <HTMLInputElement>document.getElementById('tenancyName');
    businessInput.addEventListener('keyup', _.debounce(this.checkTenantName, 1000));

  }

  checkTenantName() {
    this.taken = true;
  }

so basically, what is happening is that I'm using the debounce function from lodash to call a function after the user has stopped typing for 1s now the function does fire but the register__warning doesn't get the .taken class

Im not sure what im doing wrong.. any help would be appreciated

EDIT

I have put a console.log() in the checkTenantName() function like so

checkTenantName() {
    this.taken = true;
    console.log(this.taken);
}

and I get true returned in console.. so Im not sure why my div wouldn't be getting the .taken class

Thanks

Pengyy
  • 37,383
  • 15
  • 83
  • 73
Smokey Dawson
  • 8,827
  • 19
  • 77
  • 152
  • Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – ConnorsFan May 07 '18 at 01:28

1 Answers1

2

You are accessing this which means for the component class itself, so you need to keep original context while running checkTenantName function via bind(this) or use arrow function.

// use bind(this)
businessInput.addEventListener('keyup', _.debounce(this.checkTenantName.bind(this), 1000));
// use arrow function
businessInput.addEventListener('keyup', _.debounce(() => this.checkTenantName(), 1000));

Refer demo.

Pengyy
  • 37,383
  • 15
  • 83
  • 73