Home > OS >  Angular change input value when clicking at a div
Angular change input value when clicking at a div

Time:01-31

Impleminting a function of changing the Input value when clicking at the img - it should take the image id and passing the selected id or the key to the input as a text and submiting the form.

I tryed by using Jquery to change the text of the input but when submiting the form is not taking the new value:

        $(document).on('click', '.img-block > img', function(){
            $('.img-block > img').each(function(){
              $(this).removeClass('active');
            })
            $(this).addClass('active');
            var text = $('#app-icon-input');
            text.val(this.id);
            elementSelected = $(this);
            typeSelected = false;
          });
          

but while I'm using Angular $scope it should change the input field on changing and clicking at the imge selected

CodePudding user response:

You can add a (click) directive on the img tag to execute a function that changes the value of a variable of your component that represents the value of the input.

html code

<img (click)="handleImgClick('imgId')" src="./assets/test.png" />

<input [(ngModel)]="inputValue" />

ts code

inputValue: string = ""; 

constructor() {
}

handleImgClick(id: string):void {
    this.inputValue = id;
}

So, there is no need to use jquery in this case!

Also, I would start to move from the use of 'var' to 'let' or 'const'.

  • Related