jQuery THIS trap in Angular 2

Because of the access scope for jQuery, you must be careful when you use the jQuery in the  Angular. such as for this code  :

resultList  :string[] = [];
       myarray  :string[] = ['s1','s2','s3'];

       ............
                this.resultList.push('testS1');
                jQuery.each( this.myarray, function( index, v ) {
                        this.resultList.push(  v );
                });
       ...............

The error you will get will be :
Cannot read property ‘push’ of undefined

Correct way is:

       resultList  :string[] = [];
       myarray  :string[] = ['s1','s2','s3'];

       ............
                this.resultList.push('testS1');
                let __mythis = this;
                jQuery.each( this.myarray, function( index, v ) {
                        __mythis.resultList.push(  v );
                });
       ...............
Advertisements