2

My problem is when I change input field value using javascript, it won't change in ngModel value.

For example:

//html 
<input type="text" name="date" [(ngModel)]="date">

Typescript

  var date : any;
    constructor(
            // some code
        ) {
            this.date="10:10:2016";
        }

When I console 'date' it will show 10:10:2016

After executing this Javascript code

document.getElementsByName("date")[0].value = "15:10:2016";

text field will change its value, but ngModel value won't change

btw I use jQuery datepicker

2
  • Is it banner or date ? Commented Jan 9, 2017 at 16:56
  • date sorry my mistake Commented Jan 9, 2017 at 16:56

2 Answers 2

1

You need to trigger an input event on the element so Angular knows that something changed. Look at the answer here: Change AngularJS input text value using javascript

Sign up to request clarification or add additional context in comments.

4 Comments

tried $('[name="date"]').keydown(); $('[name="date"]').keyup(); $('[name="date"]').keypress();; $('[name="date"]').blur(); but nothing works
try $('[name="date"]').trigger("input")
How are you checking whether ngModel is changing on the backend?
i use test function on button click to console it testing(){ console.log(this.date); }
1

you need to execute the javascript code in ngAfterViewInit

ngAfterViewInit() {  
  let myNewDate= document.getElementsByName("date")[0].value = "15:10:2016";; 
  this.date = myNewDate;
}

and assign the value to your date variable.

2 Comments

Thanks , this code works fine . but i use external js (jquery) to assign value to input field and i think i found a solution..
Use jquery input function in ngView and assign value of input field value to ngModel now i don't have access to my pc to test this code. Will post solution after testing :) , your answer helped me to solve my problem .. thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.