Module 3.1: Breaking down the Component
Let's look at header.component.ts
this in Angular
Inside functions, whether the constructor function, a lifecycle function, or a function that we created… if you want to access a variable in the global scope, you need to preface that variable with “this.” to indicate it references the overall component. This is very similar to react. Notice in our login()
and logout()
methods, that we've use this.nameToDisplay
, becuase nameToDisplay
is a global variable.
Conditional Rendering in Angular
Right now the Register, Login, and Logout buttons are ALWAYS visible. That doesn't look great. Let’s hide the Logout button to start with, and when someone logs in, then hide the Register and Login buttons instead. Angular has a way of controlling visibility with “*ngIf”. Let’s look at this example:
Only the img.png
will be shown. If the content inside the quote marks is “truthy” then the tag will be shown. On the other hand, if the content inside the quote marks is “falsy” then the tag will be hidden. We can even apply this to a <div>
tag and control the visibility for an entire section of HTML, it doesn’t have to be a lonely image tag.
We only want the Register and Login buttons to appear if the nameToDisplay
variable is an empty string… and the Logout button to appear only if the nameToDisplay
variable is NOT an empty string. Since empty strings are falsy, we could simply write it as below in our header.component.html
file:
Cool, serve your website and try it out! On page load you should no longer see the Logout button. After logging in, you should no longer see the Register or Login button - instead you should see logout.
Next, we'll learn about data binding in Angular.
Last updated