https://blog.kevinchisholm.com
In this video, I’ll explain how to use the Angular Click attribute.
The Angular Click attribute makes it very simple to set up a click event handler for a DOM element. In this example, I’ve taken a couple of different approaches. The first approach is providing a method name to the click attribute. So, when this button is clicked, I’m going to execute this method setMessage1, which is a property on our component, which we’ll see in a moment.
In the second button when that is clicked, I’m providing an expression. So, this expression will be evaluated. And here I’m saying the content, which is a property in our component, is set to the string “This is message 2.”
And then in this third button, when it's clicked, I’m evaluating this expression and I’m saying the count property on our component, is incremented by one. So, let’s look at our component, and we’ll see there’s a count property, which I just mentioned, set to number, and then a content property, which is a string.
And there’s also this set message method. So, when that method is executed, I’m saying that the content property, this component, is set to “This is message 1.” So, before we go too much further with the code, let’s see how this all looks.
So, when I click button # 1, it sets the content to “This is message 1.” When I click button # 2, it sets the content to “This is message # 2.” And when I click this button, its text changes “I’ve been clicked however many times it’s been clicked times.”
So why these things happen here. Well, with button # 1, I said call the set message method, and the set message method changes the text to the content “This is message 1.” So, when I click the first button, I should see “This is message 1,” which is what I see.
For the second button, I should see “This is message 2.” And that’s happening because I’m evaluating an expression here for when the button is clicked, so it just directly sets the content property to message 2.
And once again, for message 3, it increments the count property by 1. So, once again, in the page, when I click the first button it says, “This is message 1,” second button, “This is message 2,” and the third button just increments count.
And that’s because for each button, I’ve set the click attribute and it’s evaluating whatever I provide. In this case, it’s evaluating an expression, or a method on a component, and in these two cases, it’s actually evaluating an expression that I provide right here in line.
If you found this video helpful, you can subscribe to my channel by clicking the red "Subscribe" button right under the video. You can also take a look at my blog, where there are many articles and tutorials about web development.
Thanks very much for watching.