Module 2: Components & Routing
Goals
In this module, our goals are to
Learn more about “components”
Learn about importing and exporting
Build our own components
Set up routing between pages
Analyzing Components In Depth
In Angular, each “component” is built from 4 files:
HTML file - contains the HTML for that component. If the component is the header, this HTML file probably contains a
<nav>
tag, a few<div>
tags, probably with class="navbar navbar-default navbar-fixed-top" in there somewhere... Standard HTML code.CSS file - this contains the CSS rules that will apply to this component. Any CSS rules you place here will ONLY work for this component and NO others. If you have 2 different components each with an unordered list, and you want all unordered lists to have red text, you have to place the CSS rules inside each component’s CSS file. (Or, place the rules in the global styles.css file).
SPEC file - this file is used for testing. This is outside the scope of this project, ignore this file.
TS file - This is the TypeScript file where we write all our logic, mostly coded in JavaScript. (Eventually, you’ll realize that TypeScript just enforces a structure to our JavaScript files, it’s nothing game changing… all of your JavaScript knowledge still applies here.)
Let’s look at this TypeScript file more in depth.
Structure to TypeScript Files:
At the top of each file are all of our “import” statements.
Next up, we have our @Component. This tells Angular that we are building a Component, as opposed to building something else for Angular.
Selector - this is the HTML tag for the component we are building. For our current file, it’s “app-root”... so anytime we see
<app-root></app-root>
in an HTML file, it will load this component.TemplateUrl - this is the path to the HTML file.
StyleUrls - this is the path to the CSS file.
Then, we “export” our “AppComponent”
Inside of these curly braces is a variable named “title”. The “title” variable is set equal to a string.
Inside these curly braces is where all of our fancy JavaScript knowledge will be put to work.
App Root
Let’s talk more about that “selector” being “app-root”. Again, anytime we see <app-root></app-root>
in an HTML file, it will load this component. In fact, it will insert the component’s styled HTML in between the <app-root></app-root>
tags. Take a look at the index.html
file.
Notice the <app-root></app-root>
tags? What happens is... when our page (index.html) is loaded in a browser, Angular takes the contents of our “app-root” component, and sticks it inside the <app-root></app-root>
tags. This is very similar to how react does this with a div with an id of "root".
Next, we'll build our header component!
Last updated