[toc]
🏃 RUSH! There's going to be some stuff that will be skipped temporarily
Moe: "Woah, hey, you didn't pay for the beer."
Homer: "Can't someone else do it?"
[Moe and homer laugh together. As Homer starts to leave the tavern, Moe cocks and points a shotgun at him and clears his throat.]
Moe: "Seriously, give me the money."
--The Simpsons "Trash of the Titans" (Season 9, episode 22) (1998)
We use libraries to make our lives as developers easier. We can focus on solving or specific problems if we don't have to spend time figuring out how information flows throughout our project.
When it comes to web based applications, there are two very different places code can exist: in the user's browser ("front end") and on the host's server ("back end").
For web app development, consider the front end as what the user interacts with and sees, while the back end contains the logic and manipulation that the user doesn't need to worry about. Similar to how an old mechanical clock works. The front end would be the face with the 12 numbers and two moving hands. The user only needs the clock face to determine the time. The back end for the clock would be the various cogs, wheels, and power source.
In this chapter, we will use Angular as our front-end JavaScript framework. Angular dictates how to structure our files, as well as how information flows between them. It also contains a number of tools to help us bind other part of the application users see in their web browsers.
NOTE: There are many ways to create front-end web applications with JavaScript. Popular frameworks for JavaScript include React, Vue, Ember, etc.
Angular is a framework that breaks the overall project into smaller pieces, each with their own code and styling. Angular then combines all of the pieces to create the full web page.
Taking this modular based approach allows us to separate the individual pieces of our application so we can focus on them one at a time.
Through these next three chapters, we will look at the basic building blocks of an Angular application.
A template provides the general structure for a web page. It identifies where different elements get placed on the page, but it does not fill them with content. Think of a template as an outline for what we want the page to look like. No details yet, just defined space where information needs to be added.
To demonstrate how helpful templates can be, you will need a copy of the LaunchCode Angular projects repo:
-
Fork the angular-lc101-projects repo on GitHub.
-
In a terminal, navigate to the folder you've been using to make clones of your LC101 repos. Clone your fork (
git clone https://github.com/<your_user_name_here>/angular-lc101-projects) The repo contains a lot of Angular code that we will soon go over. We'll go over this shortly.$ cd lc101 $ git clone https://github.com/${github_username}/angular-lc101-projects -
Open VS Code and and open the
angular-lc101-projectsfolder. This folder will be used as a workspace. -
Navigate to
lesson1/examples/noTemplate. -
The code in
noTemplate/index.htmlbuilds a simple 3-column webpage. It defines the location for each heading, unordered list, and button. ThenoTemplae/style.cssfile specifies the font, text size, colors, etc.<body> <h1>Hello, Screen!</h1> <div class="row list"> <div class='movie'> <h4>Movies</h4> <ul> <li>Hidden Figures</li> <li>The Princess Bride</li> <li>Ferris Bueller's Day Off</li> </ul> <button class='movie'>More</button> </div> <div class='school'> <h4>Education</h4> <ul> <li>LaunchCode</li> <li>Monsters University</li> <li>My HS</li> </ul> <button class='school'>More</button> </div> <div class='hobby'> <h4>Hobbies</h4> <ul> <li>Knitting</li> <li>Cycling</li> <li>Shark Rodeo</li> </ul> <button class='hobby'>More</button> </div> </div> <hr> <div class="links"> <h2>Links</h2> <a href="https://www.launchcode.org/" target="_blank">LaunchCode</a> <br> <a href="https://www.webelements.com/" target="_blank">WebElements</a> </div> </body>
In the Explorer sidebar in VSCode, right click in the
noTemplate/index.htmlfile and select "Copy Path" then open a new tab in your browser and Paste the address into the address bar. (You may want to prepend it withfile:///and replace the back slashes with forward slashes.)
We could drastically improve the appearance and content of the page by playing around with the tags, classes, styles, and text. However, any changes we want to make need to be coded directly into HTML and CSS files.
This quickly becomes inefficient, especially if changing the items involves multiple blocks of code.
Each section in a template contains one or more blanks where specific items need to be added. Separate JavaScript code sends data to the template to fill in these blanks, and the data can change based on a user's actions.
<body>
<h1>{{mainHeading}}</h1>
<div class="row list">
<div class='movie'>
<h4>Movies</h4>
<ul>{{movieTitles}}</ul>
<button class='movie'>More</button>
</div>
<div class='school'>
<h4>Education</h4>
<ul>{{schoolNames}}</ul>
<button class='school'>More</button>
</div>
<div class='hobby'>
<h4>Hobbies</h4>
<ul>{{hobbies}}</ul>
<button class='hobby'>More</button>
</div>
</div>
<hr>
<div class="links">{{headingAndLinkList}}</div>
</body>NOTE: Don't change the HTML in
noTemplate/index.html. We haven't yet covered the Angular work needed to make use of this template syntax.
The HTML looks similar to the previous example, but saves about 16 lines. It provides the same <div></div> structure but replaces some of the specific text between tags with placeholders, also called handlebars or mustaches.
Each item listed inside {{}} refers to data that will be passed into the template and automatically formatted. Form example, the template converts {{movieTitles}} into a sequence of <li></li> tags.
By defining our templates in an even more general manner, we could replace the h4, ul, and button structure with a single placeholder.
<body>
<h1>{{mainHeading}}</h1>
<div class="row list">
<div class='movie'>{{movieContent}}</div>
<div class='school'>{{schoolContent}}</div>
<div class='hobby'>{{hobbyContent}}</div>
</div>
<hr>
<div class="links">{{linkContent}}</div>
</body>By using a template to build the website, changing the list of movies, schools, or hobbies involves altering something as simple as an array or object. After changing the data, the template does the tedious work of modifying the HTML. The list of movies would update automatically if we add Up to our favoriteMovies array, which then gets passed into {{movieContent}}. We do not need to worry about re-coding any of the tags.
If we add a search box to our website, a user could enter "NASA images", "giraffe gif", "movie trailers", etc. We cannot know ahead of time what a user will request, but we want our website to be able to display any relevant requests.
Besides making it easier to organize and display content, templates also allow us to create a dynamic page, meaning that its appearance changes to fit new information.
For example, we can define a grid for displaying photos in rows of four across the page. Whether the images are giraffes, tractors, balloons, or whatever doesn't matter. ==The template sets the layout and the code feeds in the data.== If more photos are found, extra rows are produced on the pages, but each row shows 4 images.
Templates must be used anytime we create a webpage that response to a changing set of data, especially if that data is unknown to us.
Templates allow us to decide where to display data on our webpages, even if we do not know what exactly the data will be. Information pulled from forms, APIs, or user input will be formatted to fit within our design.
NOTE: The figure above is called a mockup or "wireframe" of a webpage. Mockups can be used to create unit tests called "mock objects". The main reason to create such mockups is to be able to test one part of a software system (a unit) without having to use dependent modules. We did this before back in Chapter 14.
You can create one of these with programs like Photoshop, GIMP, Illustrator, or Inkscape. But more than likely, your naïve Mac-using employer will want you to use something like Balsamiq. But I ain't paying for software with a subscription service (cough Adobe cough). As usual, I want to find something that is Free and Open Source Software (FOSS). I'm still looking for something good.
In the above figure, the black outlines represent different structures defined by the template. Each structure governs a specific portion of the screen. As data gets fed into the template, the appearance of the page changes.
If no data is sent to a particular structure, that part of the screen remains empty because the space is still reserved. Other components of the page will work around that space.
Each Angular project contains a standard file structure.
📁 project-name
|- 📁 src
|- 📄 (support files)
|- 📁 app
|- 📄 index.html
|- 📄 main.ts
|- 📄 style.css
|- 📄 test.ts
|- 📄 polyfills.ts
|- 📁 (app files and subfolders)
All of the project files (and there will be a lot of them) are stored in the single, top-level folder, project-name, which contains a src folder and a set of support files.
NOTE: When you start a new Angular project, do not worry about the support files. These will be generated automatically, and they take care of the routine technical details for making your project run smoothly.
src contains the app folder, and five important files: index.html, main.ts, style.css, tests.ts, and polyfills.ts. We will explore these files in more details in section 28.4. For now, recognize that they control how the Angular project operates.
The app folder contains the files and subfolders needed to control the nitty-gritty details of displaying a webpage. For your projects, most of your time and effort will be spent modifying the contents within app.
Finally! The part you've been waiting for!
Angular uses its own set of command line instructions to create, update, and launch projects. Before you dive too deeply into the Angular lessons, you will need to install the Angular CLI on you computer.
NOTE: There is a newer version of Angular than 8.2.2, and you might see NPM sa something like
npm WARN depricated request@2.88.2(which involves a dependency package that version of Angular used, but for the purposes of this lesson is not important right now.) however for any of the stuff to work for LC101, we need to use that specific version. After LC101 is over, and your last assignment checked by the TA, you can upgrade Angular to your liking.
- Open up the terminal or the terminal panel in VS Code. (
CTRL+Shift+backtick) - Run this specific command
npm install -g @angular/cli@8.2.2
Note: If it asks if you want to share "anonymous usage data with the Angular Team at Google", type
Nfor no. If the installer prompts you to make any other choices, accept all the default options.
The NPM command installs the CLI globally (hence the -g flag), which means that Angular command will work regardless of the folder you have open. Most of the time when you use packages for specific objects, installing globally might not be the best ideal, but for things like TypeScript and Angular, they are.
Angular commands begin with the keyword ng (for Angular) and the most commonly used include:
ng new(orng n) -- Creates a new Angular project in the current directory.ng generate(orng g) -- Creates new files within an existing project.ng serve(orng s) -- Compiles a project and launches it in a form that can be displayed in a browser.
For a complete list of commands, refer to the Angular documentation.
For the "HTML Me Something" assignment, you created an account. Since you will modify Angular projects for over several lessons, you need access to GitHub to download starter code and store your progress.
An any time we need to look up something related to Angular, the website we should look at is angular.io not AngularJS.
With all that said, let's get started!
The goal here is to create a minimum working template for a webpage. It will serve as a jumping-off point for later exercises and studios, so take as much time as you need to get comfortable with the basics.
First, let' use the terminal to create a folder for all your angular projects. This will be a new folder, not one that you cloned or forked. Once that is done, navigate into the new folder and create your first Angular project.
$ mkdir angular_practice
$ cd angular_practice
$ ng new my-project-name
? Would you ke to add Angular routing? (y/N) N
? Which stylesheet format would you like to use? CSSThis next part is going to take a little time to create. But when it is done, you may want to open the new Angular project folder in VSCode.
- The
srcfolder holds the files and source code needed for the project. - The
appfolder holds the content for the web page. Although the page is treated as a single entity, it actually consists of multiple pieces.appholds these different parts and establishes links between them. We will modify some of these files soon. index.htmlis the highest level for displaying content. Anything added to this file will appear on every page within a website.main.tsimports the core methods required to make everything work. It also imports the content from theappfolder.styles.cssholds the global style settings for the entire website.
For every new project, Angular automatically sets up the code to make the different parts communicate with each other. As your skills grow during your career, you may need to learn how to modify these files. For now, however, leave the following files alone:
- DO NOT TOUCH THESE TYPESCRIPT FILES:
main.ts,test.ts, andpolyfills.ts. - DO NOT TOUCH THESE FOLDERS:
e2e,node_modules, andenvironments. - DO NOT TOUCH THE GENERATED JSON FILES: If it ends with
.json, no touchy! - The
assetsfolder is a "Maybe touch." It holds user defined files that support a project. Examples include: JavaScript Code, image files, gifs, or video clips. The exercises in the next chapter will use this folder, but we will leave it empty for this lesson.
ng new creates all the files required to launch a functioning web page. You have not added any content yet, but Angular provides a standard starting point that allows you to check if everything works.
Before sending an Angular project out in the world, you should preview it locally in a browser. Any changes you make to the project files will be reflected only on your screen so you can play around with the code without worry.
NOTE: Even though you view our work in a browser, "local" means no one else can access your webpage, since it is stored on your computer. If you want to share your local page with someone, they'll have to look over your shoulder or do a screen share.
To launch your new web page, use the Terminal to navigate into the project folder, then enter the command ng serve. (I think I mentioned how to do this similarly in Python, but thanks to one of Angular's dependencies called Express, you can do it with Node.js too...or at least that is the dependency I think makes that possible.)
$ cd my-project-name
$ ng serveBe prepared to wait...the compiler requires some time to build and deploy even small projects, and it may be a few moments before you see any action in the terminal. If no errors occur, "Completed successfully" message eventually appears.
🎗️ TODO: Wasn't there an article on dev.to about better management of node dependencies and assets to make compilation faster? I know I have it book marked somewhere. Not sure if Yarn or Webpack are involved.
The important part of this feedback is the localhost line, which provides a URL for viewing your work in a browser, as if it was posted online (with the http:// prefix) rather than how it would appear offline (with the file:/// prefix). Copy the URL and paste it into the address bar of you web browser.
🎗️ TODO: Copy part of the processing log here that includes the line showing the localhost address.
NOTE: Angular will likely use port 4200 (
:4200) which is an important part of thelocalhostaddress you are copypastaing. Make sure that no other application is using that port.
ng serve allows you to view your project in a browser by running a series of tasks in the background. It's not magic, just the tedious mechanics that you don't need to set up yourself.
ng serve performs the following tasks:
- Compiles and analyzes your Angular files to build HTML and JavaScript files that can be run in a browser.
- This step throws errors if you try to serve code that contains syntax errors or other errors.
- You will learn more about the different types of files that are compiled in the coming sections.
- Starts a web server on your computer that serves the built version of your Angular project.
- Your Angular project is viewable at the web address
http://localhost:4200/
- Your Angular project is viewable at the web address
NOTE: Angular projects are written in TypeScript, your web browser can run HTML, CSS, and JavaScript. In order for your Angular project to run in the browser, the TypeScript code has to be converted into JavaScript. The conversion from TypeScript to JavaScript happens during the build phase of
ng serve.
🎉🥳😄 CONGRATULATIONS! You have a function webpage. You should see the following in your browser:
This is the default forma created by ng new, but your chosen project name will replace my-project-name in the title. ( 🎗️ TODO: Hopefully I won't need to rename that. 🤪 ) The links lead back to selected pages from the angular.io documentation.
Feel free to play around a little before continuing. Don't worry about breaking anything. If necessary, you can always start another new project.
In VSCode, open the four files within the app (AND folder.src)
src/index.html(which you won't need to make any changes here)src/styles.css(So you can change the<body>element's appearance and any global changes)src/app/app.components.html(to edit the content in<app-root>)src/app/app.components.css(to change the styles of the components insrc/app/app.component.html)src/app/app.component.tssrc/app/app.module.ts
Modify the code to accomplish the following:
- Find where your project name is assigned to the
titlevariable. Replace it with a different string. - Change one
h2heading to anh3. - Change the color for the "Welcome to..." heading.
- Change one of the lines to send users to your favorite website.
- Replace the Angular shield with a different image.
After making each change, save your work. Your webpage should automatically refresh.
NOTE: While files did you modify?
- Mostly
app.component.htmlandapp.component.css?- 🎗️ TODO: What changes the background color if the page has no
<body>?
- More than likely, those are manipulated in the
src/styles.cssfile rather than thesrc/app/app.component.cssfile. (I fixed this. They probably should have mentioned that.)- For global changes, you should edit
src/styles.css(and don't forget to add theactually you don't. Angular will do that.).<link rel="stylehsheet" href="./styles.css">insrc/index.html- For component changes, edit the
src/app/app.component.css
Don't worry if you got stuck on some of the tasks. This was an time for experimentation. As long as you tried something and saw the result, you still learned something valuable.
What's up with that? Why do the links that have a
target="_blank"attribute (which tells the browser to open it in another tab) have arel=nopennerattribute? Supposedly, it's for some security thing. ( 🎗️ TODO: Explain later. )
ng serve will continue to run until you press ctrl+c in the terminal. Go ahead and interrupt the process now. If you try refreshing your page, you will see an error.
Now let's take a look at the different project files.
Quick Recap
ng new ${project_name}to create a new Angular project in a project folder called${project_name}.
- Alternatively, use
ng generateto create an Angular project from an existing project. (We didn't go over this too well.)cd ${project_name}so that you remember where to runng servelater.- Most of the files (for now) that you will be working on will be in the
src/appdirectory.ng serveto launch a the project (remember tocdinto it first!)
- The project will be seen at
http://localhost:4200/- The project should refresh automatically when you make changes to files.
- Use
ctrl+cto shut down the server when you are done.
NOTE: Looks like some of those things I suggested were actually applied here in this section. They should have mentioned it sooner.
In VSCode, navigate to the src folder and open index.html and examine the code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>MyProjectName</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
</html>You have seen most of the HTML tags before, but look line 12. The <app-root> tag representa a key idea behind building template. Angular allows us to define our own tags, which are used as another type of placeholder in an HTML file. In this case, <app-root></app-root> reserves space on the webpage for information supplied by other files. Line 12 essentially says, "Display all the content from the app folder here."
As we add more pieces to our template, we will define specific tags to help us arrange the different items on the screen. This makes it easier for use to keep track of our content. For example, if we wanted to build a web page that contains a shopping list, a list of movies to watch, and family photos, we can define the tags <grocery-list>, <movies>, and <family-photos>, respectively. With these tags, we can reference specific content whenever we want and clearly place it on a page. The tags also make it easy to play with new styles and formats for our grocery list without changing much code or altering the appearance of the movie list or photos.
Most of our work with Angular will take place within the app folder, so let's look over some of the files in it.
One way of changing the color of the "Welcome to..." heading would be to open the app.component.css file and add some styling:
h1 {
color: brown;
}We can freely modify this file, but the CSS instructions only affect the HTML files within app. Also the code in app.component.css overrides any CSS found in the higher level styles.css file. (Remember this is the nature of how Cascading Stylsheets work.)
This is the pattern for Angular. CSS instructions further down in the file tree have a higher priority. ( 🤓 Actually, if two stylesheets have the same definition, the file future down the list overwrites it. The CSS files in app are loaded after styles.css is loaded.) If the app folder contained a subfolder with its own .css file, then those instructions would be applied to the HTML files within that subfolder.
Example: Here's a sample of the default code inside
app.component.html:<div style="text-align:center"> <h1> Welcome to {{ title }}! </h1> <img width="300" alt="Angular Logo" src="image path..."> </div> <h2>Here are some links to help you start: </h2> <ul> <!-- List items here... --> </ul>
app.component.html contains the structure and most of the text seen on the "Welcome to..." page. Notice the placeholder {{title}} in line 3. This gets filled with data passed in from another file, and it allows us to modify the content on the page without revising the HTML.
app.component.html serves as the main template for your webpage. This file will usually NOT hold a lot of HTML code. Instead, it will contain many placeholders for content defined elsewhere in the project.
Later in this chapter, you will learn how to add new components to the app folder, as well as how to arrange them in the HTML file.
Example:
app.component.tsimport { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'my-project-name'; }
app.component.ts performs several important functions with very few lines:
- Line 4 defines the
<app-root>tag, which we saw on line 12 ofindex.html. This tag can also be used in any files that import theAppComponentclass. - Line 5 imports
app.component.htmlwhich we examined above. - Line 6 imports
app.component.csswhich applies styles to the HTML file. (Well, not everything. You'll still want to editstyles.cssto change the<body>element.) If you set a different color to the "Welcome to..." sentence in the Try It tasks, this is why changing the CSS file worked. - Line 8 makes the
AppComponentclass available to other files.
Take a look at app.component.html again. We mentioned the {{title}} placeholder earlier and said that it gets filled with data from a different file. Line 9 in app.component.ts supplies this data by assigning the string 'my-project-name' to the title variable. Changing 'my-project-name' to a different value alters the web page.
Example:
app.module.tsimport { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
Just like before, there is a lot going on within very few lines.
- Lines 1, 2, and 8 import and assign the core modules that make Angular work. This is part of the automatic process, so don't play with these (yet).
- Line 4 imports the class
AppComponentfrom the local fileapp.component.ts. - Line 4 also pulls in references to any other files lined to
app.component.ts. - Line 7 declares the imported local files as necessary for the project.
- Line 12 exports the
AppModuleclass and makes it available to other files.
app.module.ts does the main work of pulling the core libraries and local files. As new parts are added to a project, the import statements, imports array, and declarations array update automatically. We do not have to worry about the details for adding the critical code ourselves.
Enough detail. Let's explore some more.
If you didn't complete all of the Try It tasks from earlier, attempt them now, After that...
-
Run
ng servein the terminal to launch your webpage again. -
In
app.component.ts, declare and assign two variables in theAppComponentclass:nameanditemList.nameholds your name.itemListis an array holding at least 4 items.
export class AppComponent { name: string = 'Barbara Liskov'; itemList: string[] = ['item1', 'item2', 'item3', 'item4']; }NOTE: Instead of using the strong TypeScript variable declarations in step 2, we could substitute a pattern more like JavaScript (You know what, do it in TypeScript like above. PRACTICE!):
export class AppComponent { name = 'Brendan Eich'; itemList = ['item1', 'item2', 'item3', 'item4']; }
-
Replace Line 4 in
app.component.htmlwith<h1>{{name}}'s First Angular Project</h1>. Save your work and check to see if the web page shows the new heading. -
Modify the
<li></li>elements inapp.component.htmlto display the elements fromitemListsin an unordered list. Be sure to use placeholders like{{itemList[0]}}between tags. -
Define a
rectangleobject inAppComponentthat has keys oflength,width, andarea. Assign numbers tolengthandwidth, and haveareabe a function that calculates and returns the area.rectangle = { length: 5, width: 6, area: function() { return this.length * this.width; } }
-
Add a
<p></p>element inapp.component.htmlto display the sentence with the placeholders in the following code snippet.<p>The rectangle has a length of {{rectangle.length}} cm, a width of {{rectangle.width}} cm, and an area of {{rectangle.area()}} cm^2.</p>
Each of the files in the app folder contains the word component in their name. This results from the fundamental ideal idea behind Angular. Each template for a web page is constructed from smaller pieces, and these pieces are the components.
Our next step is to take a closer look at these building blocks within a template.
In Angular, a component controls one part of the page, called a view.
Angular builds a web page by combining multiple components together. Splitting our page into individual components makes our application more organized. It also increases our ability to focus on one section of our web application at a time.
Everything in Angular centers on the idea of building a webpage from separate, smaller pieces. We must understand how to get these pieces to work together, and that begins by exploring what makes each individual component. In order to build a reliable component, we must understand how each of its parts work and interact.
In the terminal, navigate back to the angular_practice folder and create a new project called component-practice.
$ cd ..
$ ng new component-practice
$ cd component-practiceOpen the src/app/app.component.html file in VS code. Remove ALL of the code and replace it with an empty div element.
<div>
</div>The stage is set for a closer look at components.
Angular components consist of 4 files:
- An HTML file (
.html) - A CSS file (
.css) - A TypeScript file (
.ts) - A TypeScript test file. (
.spec.ts)
These files are put into their own folder in the src/app directory
🎗️ TODO: What if we made a bash script that could generate these files?
#!/bin/bash # File: component.sh project=${1} component=${2} cd ${project}/src/app mkdir ${component} cd ${component} files=(html css ts spec.ts) for file in "${files[@]}"; do touch ${component}.component.${file} doneWe could then generate these files in one command
$ ./component.sh path/to/project component_name
Looking at the files tree, we see that all four files contain the name of the component header in a folder called header.
📁 src
|- 📁 app
| |- 📁 header
| | |- 📄 header.component.css
| | |- 📄 header.component.html
| | |- 📄 header.component.spec.ts
| | |- 📄 header.component.ts
If we add a new component name task-list the four files inside the task list folder would be called
task-list.component.html- holds the HTML required for the task-list and no other component.task-list.component.css- holds the styles fortask-list.component.htmltask-list.component.ts- holds the TypeScript code that only applies to the task-list component.task-list.component.spec.ts- holds the unit tests for task-list
Each component is a smaller part of an overall web application. The main component, app, serves as a base structure and it comes standard with all Angular applications. It is the container that holds all of the other components, and it organizes them into the web application.
When you generate a new component using the Angular CLI, it is automatically added to app.
😠 NOTE: I really wish they would stop writing this in such a way that I write something on how I would approach a solution I though they didn't think of with me having to write it anyway. I'M PRESSED FOR TIME HERE!
To create a new Angular component, we use the ng generate command.
$ cd src/app
$ ng generate component ${component_name}
⚠️ WARNING! A common mistake is to create a new component in the wrong location, say in thesrcfolder instead of theappfolder.
ng generateplaces the new component folder within your current directory. Use the terminal to navigate to where you want the component to go before running the generate command.
creating a task-list component looks something like this:
$ ng g component task-list
CREATE src/app/task-list/task-list.component.html (24 bytes)
CREATE src/app/task-list/task-list.component.spec.ts (643 bytes)
CREATE src/app/task-list/task-list.component.ts (280 bytes)
CREATE src/app/task-list/task-list.component.css (0 bytes)
UPDATE src/app/app.module.ts (406 bytes)From the output, we see that ng generate command creates four new files in the src/app/task-list folder.
NOTE: Recall that
ng gis an alias forng generate.
- Use the terminal panel (
CTRL+SHIFT+backtick) in VSCode to navigate into theappfolder. - Run
ng generate component task-list. - Add a
headercomponent by runningng generate component header - List the files in the
app,app/task-listandapp/headerdirectories.
$ pwd
some/path/to/angular_practice
$ cd component-practice/src/app
$ ls
app.component.css app.component.html app.component.spec.ts app.component.ts app.module.ts
$ ng generate component task-list
CREATE src/app/task-list/task-list.component.html (24 bytes)
CREATE src/app/task-list/task-list.component.spec.ts (643 bytes)
CREATE src/app/task-list/task-list.component.ts (280 bytes)
CREATE src/app/task-list/task-list.component.css (0 bytes)
UPDATE src/app/app.module.ts (406 bytes)
$ ng g component header
CREATE src/app/header/header.component.html (21 bytes)
CREATE src/app/header/header.component.spec.ts (628 bytes)
CREATE src/app/header/header.component.ts (269 bytes)
CREATE src/app/header/header.component.css (0 bytes)
UPDATE src/app/app.module.ts (488 bytes)
$ ls
app.component.css app.component.spec.ts app.module.ts task-list
app.component.html app.component.ts header
$ ls task-list/
task-list.component.css task-list.component.spec.ts
task-list.component.html task-list.component.ts
$ ls header/
header.component.css header.component.html header.component.spec.ts header.component.tsIn order to communicate with the new components, app.module.ts needs new import statements. Fortunately, ng generate updates the code automatically, so we don't need to worry about taking care of this task ourselves.
Before using
ng generate:import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }After using
ng generateto generate theheaderandtask-listcomponents:import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { TaskListComponent } from './task-list/task-list.component'; import { HeaderComponent } from './header/header.component'; @NgModule({ declarations: [ AppComponent, TaskListComponent, HeaderComponent ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
Angular updates app.module.ts by adding new import statements on lines 5 and 6 as well as expanding the declarations array on line 9.
Note: Generating a new component automatically updates
app.module.ts. However, if you delete an component, you must MANUALLY remove its import statement and its name in thedeclarationsarray.
Run ng serve. The page is empty because we removed everything from app.compoent.html and replaced it with a div.
Add an <app-header></app-header> tag inside the div.
<div>
<app-header></app-header>
</div>Save your changes and wait for the page to refresh in the browser. You should see header works! at the top of the page.
This is another helpful feature with Angular. When you correctly implement a new component, confirmation text appears.
How did <app-header></app-header> make this happen? Let's look inside the header.component.ts file.
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
constructor() { }
ngOnInit() {
}
}Line 4 defines the HTML tag for the header component to be app-header. If we changed the string to 'orange', we would see the "header works!" text disappear from the webpage. This is because the HTML tag <app-header> is no longer linked to the component. The string assigned in line 4 MUST match the tags used in app.component.html.
Open header.component.html:
<p>header works!</p>This is the HTML file that contains the text that appears on our webpage. Anything added to this file will appear between the <app-header></app-header> tags in app.component.html.
Try It!
Replace line 1 in
header.component.htmlwith:<h1>My header works!</h1> <p>This is not a header, but I'm adding it anyway.</p> <div style="text-align: center"> <h2>Look! A centered h2.</h2> <p>More centered text.</p> </div> <p>Not centered text.</p>Save your code and refresh the page. How does its appearance change?
- The contents of the page changed
What happens if we use
<app-header>TWICE inapp.component.html? Let's find out.<div> <app-header></app-header> <app-header></app-header> </div>
- The component was used twice!
Line 4 in header.component.ts defined the app-header tag, and line 4 in task-list.component.ts does something similar.
Modify the app.component.html as follows:
The web pages should change once again with a "task-list works" string near the bottom.
Try It! Move
<app-task-list></app-task-list>above<app-header></app-header>. How does the page change?
- This should change the order of the two components such that the
task-listappears before theheader.
Try to correctly format and place content on a webpage can be difficult, especially if you need to present lots of data or mix different formatting styles for heading, lists, plain text, etc.
Rather than deal with our header, task, and other content at the same time, creating components allows us to:
- Create a simple HTML file that serves as a framework.
- Format each piece of our content separately, without worrying about how that formatting affects other parts of the webpage.
- Easily add content to the framework by using custom HTML tags.
- Quickly relocate the component on a page just by rearranging their custom tags.
Components can be put inside other components. In essence, this is how the app component works. It is the component that holds all other components.
However, sometimes you might want to nest a new component inside of another rather than in app.
Let's assume we want to add a new component within our task-list folder. In this case, we navigate into the task-list directory and then run the ng generate component command.
$ ls
app.component.css app.component.spec.ts app.module.ts task-list
app.component.html app.component.ts header
$ cd task-list
$ ng generate component inside-task-listRunning this command nests our new folder inside of the task-list folder, and it contain the four files we would expect.
📁 app
|- 📁 header
|- 📁 task-list
| |- 📁 inside-task-list
| | |- 📄 inside-task-list.component.css
| | |- 📄 inside-task-list.component.html
| | |- 📄 inside-task-list.component.spec.ts
| | |- 📄 inside-task-list.component.ts
| |- 📄 task-list.component.css
| |- 📄 task-list.component.html
| |- 📄 task-list.component.spec.ts
| |- 📄 task-list.component.ts
When we place one component inside of another, we must pay attention to how the components interact. The nested component, inside-task-list, is called the child, while the original component, task-list, is called the parent.
- Any CSS, HTML, or JavaScript we write for the nested component (the child) only effects that component. Changes to the child do not affect the parent.
- The parent component does influence the nested one. For example, any CSS within
task-list.component.cssapplies to bothtask-list.component.htmlANDinside-task-list.component.html. - If we want
inside-task-listto have different styling, we need to add code toinside-task-list.component.cssto override the parent.
If you have not already done so, use ng generate to nest the inside-task-list component inside the task-list-component.
❓ QUESTION: EXPERIMENT! DISCOVER!
Where would could we place the
<app-inside-task-list></app-inside-task-list>element to make"inside-task-list works!"appear on the screen. Select ALL options that work.a. Place the element in
app.component.htmlb. Place the element in
task-list.component.htmlc. Place the element in
inside-task-list.component.htmld. Place the element in
index.html❗ ANSWER: a, b.
Putting it in c. will cause it to load RECURSSIVELY!
Putting it in d. will not display it at all.
#LaunchCode


