Search code examples
angularangular-components

unable to update variable in angular component


I am learning angular and I am having an issue updating a variable.

the function toggleVariable should toggle isUserNameEmpty but its not working at all

export class ServersComponent implements OnInit {

  userName = '';
  isUserNameEmpty=true;


   onUserNameUpdate(event:any){
    this.userName = (<HTMLInputElement>event.target).value;
    this.toggleVariable( this.userName,this.isUserNameEmpty);
  }

  toggleVariable(variableName,variableToToggle){
   
    if(variableName!=''){
      console.log('not empty');
      console.log('variableName: '+variableName);
      console.log('variableToToggle: '+variableToToggle);
      variableToToggle=false;
    }
    else if (variableName==''){
      console.log('empty');
      console.log('variableName: '+variableName);
      console.log('variableToToggle: '+variableToToggle);
      variableToToggle=true;
    }
  }


  clearUserName(){
    this.userName = '';
  }

}

Solution

  • You are not modifying the isUserNameEmpty property. You are only modifying the value of variableToToggle within the scope of the method. try this

      toggleVariable(variableName) {
    
          this.isUserNameEmpty = variableName === '';
    
      }