0

I am trying to manipulate a div using simple JavaScript function. But it is giving error on the variable used:

originalText is not defined

home.ts code:

declare var orginalText: any;

imports ...

export class HomePage{
constructor(){...}

ngOnInit () {

      $('#changeText').click(function(){
         orginalText = $('#content').html();
        $('#content').text("This is text changed using jquery");
      });

      $('#changeText2').click(function(){
        $('#content').html(orginalText);
    });

home.html code:

<a href="#" id="changeText">Click here to change text of div</a>
<a href="#" id="changeText2">Original Div content</a>
<div id="content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</div>

When I click on link, it says originalText not defined.

1 Answer 1

1

Just change normal function to arrow function , and access orginalText with this.orginalText ,

orginalText;

ngOnInit () {
    $('#changeText').click(() => {
        this.orginalText = $('#content').html();
        $('#content').text("This is text changed using jquery");
    });

    $('#changeText2').click(() => {
        $('#content').html(this.orginalText);
    });
}
Sign up to request clarification or add additional context in comments.

3 Comments

why do we need this arrow function, can you guide more on this ?
There is no need of arrow , it's just scope related , With normal function you can't access this.orginalText , if you want you can go 2 ways , 1. Arrow Function 2. Bind this , rest you can know from the given link in answer
Mine pleasure, Happy Coding BTW :)

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.