An Angular application is made up of components. In an Angular application, a component consists of an HTML template and a component class. From the official docs:
Components are the most basic building block of an UI in an Angular application. An Angular application is a tree of Angular components. Angular components are a subset of directives. Unlike directives, components always have a template and only one component can be instantiated per an element in a template.
In this tutorial, you'll learn how to get started with creating a grocery list manager using Angular.
You'll need Node version > 6.9.x and Node Package Manager (npm) > 3.x.x. Once you have both, try to install the Angular CLI using npm
.
npm install -g @angular/cli
After installing the Angular CLI, try to create a project using the same.
ng new AngularGrocery --skip-npm
The above command will create the project structure. Navigate to the project directory and install the required dependencies.
cd AngularGrocery npm install
To start the application web server, type the following command:
ng serve
Once the application server has started, point your browser to http://localhost:4200/ and you will be able to view the default application.
The above figure shows the application structure for our grocery list manager. The src
folder contains the source code for the default application. The app
folder inside the src
folder contains the TypeScript code. index.html
inside the src
folder is the main HTML file where the created Angular components are rendered.
By default, the application has an app-root
component. Let's create a new component called app-grocery
for creating our grocery manager app. Inside the app folder, create a file called app.grocery.ts
.
Import the Component
module from the angular-core
.
import { Component } from '@angular/core';
You'll be using Bootstrap to design the component. Download and include the Bootstrap package from the official site. Keep the files in the src/assets
folder.
Let's define the component inside the app.grocery.ts
file. The component will have three properties: selector
, template
, and styleUrls
. selector
indicates the way in which the component will be used. template
defines the HTML which will be rendered when the particular selector is used. styleUrls
defines the URL of the styles used in the component.
Inside app.grocery.ts
, once the component module has been imported, define the app-grocery
component as shown:
@Component({ selector: 'app-grocery', templateUrl: './app.grocery.html', styleUrls: [ '../assets/css/bootstrap.min.css' ] })
As seen in the above code, the component uses a template called app.grocery.html
. Create a file called app.grocery.html
inside the src/app
folder. Add the following code to the app.grocery.html
file:
<div> <h2> Grocery list manager </h2> <div class="row"> <div class="col-xs-6 col-md-4"> <div class="input-group"> <input type="text" class="form-control" placeholder="enter grocery items" id="txtSearch" /> <div class="input-group-btn"> <button class="btn btn-primary" type="button"> <span class="glyphicon glyphicon-ok"></span> </button> </div> </div> </div> </div> </div>
In the app.grocery.ts
file, add the GroceryComponent
class to export.
export class GroceryComponent { }
You need to import the newly created component inside the app.module.ts
before you can use it. Import the GroceryComponent
in the app.module.ts
.
import { GroceryComponent } from './app.grocery';
Declare and bootstrap the newly created Grocery component in the app.module.ts
file.
@NgModule({ declarations: [ GroceryComponent ], imports: [ BrowserModule, FormsModule, HttpModule ], providers: [], bootstrap: [GroceryComponent] })
Now you are all set to use the Grocery component inside the index.html
page. Remove the default component from the index.html
page and add the following HTML code:
<app-grocery>Loading...</app-grocery>
Save the above changes and restart the server. Navigate the browser to http://localhost:4200/ and you will have the Grocery component displayed.
Once an item is entered in the input text box, you need to read the item and save it in a list. To read the input, you'll make use of ngModel
, which will bind it to a variable. Add ngModel
to the input text box.
<input type="text" class="form-control" placeholder="enter grocery items" id="txtSearch" [(ngModel)]="task" />
Each time some text is entered in the input text box, the task
variable gets updated accordingly. Define the task
variable inside the GroceryComponent
in the app.grocery.ts
file. Add a variable called tasks
to keep a collection of tasks entered.
task: string; tasks = [];
On clicking the OK button, the task will be added to the tasks
collection list that you have defined inside the GroceryComponent
. Define an onClick
method inside the GroceryComponent
to handle the OK button click. Here is how it looks:
onClick(){ this.tasks.push({name: this.task}); this.task = ''; }
Add the click event to the OK button as shown:
<button class="btn btn-primary" type="button" (click)="onClick()"> <span class="glyphicon glyphicon-ok"></span> </button>
When the OK button is clicked, the new task is added to the tasks
collection list. The task
variable is also reset to clear the input text box.
Save the above changes and, on entering the task
and clicking the OK button, the task is added to the tasks
collection. To display the tasks collection, add a span inside app.grocery.html
.
<span> {{tasks | json}} </span>
Enter the task in the input box and press the OK button. You will have the tasks
variable displayed as JSON on the page.
Here is the complete app.grocery.ts
file:
import { Component } from '@angular/core'; @Component({ selector: 'app-grocery', templateUrl: './app.grocery.html', styleUrls: [ '../assets/css/bootstrap.min.css' ] }) export class GroceryComponent { task: string; tasks = []; onClick(){ this.tasks.push({name: this.task}); this.task = ''; } }
Now, since you have the added items in the tasks
variable, you can use it to display the tasks. You'll make use of the NgFor
directive to iterate the tasks
collection and dynamically create the HTML for displaying the tasks. You'll be displaying the task inside the UL element and repeating the LI using the NgFor
directive. Here is how it looks:
<ul class="list-group"> <li *ngFor="let task of tasks" class="list-group-item"> <span> {{ task.name }} </span> </li> </ul>
As seen in the above code, you iterate through the tasks
variable and create the LI element and the span dynamically. Here is how the complete app.grocery.html
template file looks:
<div> <h2> Grocery list manager </h2> <div class="row"> <div class="col-xs-6 col-md-4"> <div class="input-group"> <input type="text" class="form-control" placeholder="enter grocery items" [(ngModel)]="task" /> <div class="input-group-btn"> <button class="btn btn-primary" type="button" (click)="onClick()"> <span class="glyphicon glyphicon-ok"></span> </button> </div> </div> </div> </div> <br /> <ul class="list-group"> <li *ngFor="let task of tasks" class="list-group-item"> <span> {{ task.name }} </span> </li> </ul> </div>
Save the above changes and restart the server. Point your browser to http://localhost:4200/ and enter the task and press the OK button. Each added task will be displayed in the list below.
In this Angular tutorial, you saw how to get started with creating a grocery list manager using Angular. You learnt how to create the view for the Grocery component, add items to the grocery list, and display the added items.
In the next part of this tutorial, you'll implement the features to mark the completed items, archive the completed items, and remove the added items.
Source code from this tutorial is available on GitHub. Do let us know your suggestions in the comments below.
The Best Small Business Web Designs by DesignRush
/Create Modern Vue Apps Using Create-Vue and Vite
/Pros and Cons of Using WordPress
/How to Fix the “There Has Been a Critical Error in Your Website” Error in WordPress
/How To Fix The “There Has Been A Critical Error in Your Website” Error in WordPress
/How to Create a Privacy Policy Page in WordPress
/How Long Does It Take to Learn JavaScript?
/The Best Way to Deep Copy an Object in JavaScript
/Adding and Removing Elements From Arrays in JavaScript
/Create a JavaScript AJAX Post Request: With and Without jQuery
/5 Real-Life Uses for the JavaScript reduce() Method
/How to Enable or Disable a Button With JavaScript: jQuery vs. Vanilla
/How to Enable or Disable a Button With JavaScript: jQuery vs Vanilla
/Confirm Yes or No With JavaScript
/How to Change the URL in JavaScript: Redirecting
/15+ Best WordPress Twitter Widgets
/27 Best Tab and Accordion Widget Plugins for WordPress (Free & Premium)
/21 Best Tab and Accordion Widget Plugins for WordPress (Free & Premium)
/30 HTML Best Practices for Beginners
/31 Best WordPress Calendar Plugins and Widgets (With 5 Free Plugins)
/25 Ridiculously Impressive HTML5 Canvas Experiments
/How to Implement Email Verification for New Members
/How to Create a Simple Web-Based Chat Application
/30 Popular WordPress User Interface Elements
/Top 18 Best Practices for Writing Super Readable Code
/Best Affiliate WooCommerce Plugins Compared
/18 Best WordPress Star Rating Plugins
/10+ Best WordPress Twitter Widgets
/20+ Best WordPress Booking and Reservation Plugins
/Working With Tables in React: Part Two
/Best CSS Animations and Effects on CodeCanyon
/30 CSS Best Practices for Beginners
/How to Create a Custom WordPress Plugin From Scratch
/10 Best Responsive HTML5 Sliders for Images and Text… and 3 Free Options
/16 Best Tab and Accordion Widget Plugins for WordPress
/18 Best WordPress Membership Plugins and 5 Free Plugins
/25 Best WooCommerce Plugins for Products, Pricing, Payments and More
10 Best WordPress Twitter Widgets
1 /20 Popular WordPress User Interface Elements
/10 Best WordPress Star Rating Plugins
/12 Best CSS Animations on CodeCanyon
/12 Best WordPress Booking and Reservation Plugins
/20 Best WordPress Calendar Plugins and Widgets
/12 Elegant CSS Pricing Tables for Your Latest Web Project
/24 Best WordPress Form Plugins for 2020
/14 Best PHP Event Calendar and Booking Scripts
/Create a Blog for Each Category or Department in Your WooCommerce Store
/8 Best WordPress Booking and Reservation Plugins
/Best Exit Popups for WordPress Compared
/Best Exit Popups for WordPress Compared
/11 Best Tab & Accordion WordPress Widgets & Plugins
/12 Best Tab & Accordion WordPress Widgets & Plugins
1 /New Course: Practical React Fundamentals
/Short Course: Better Angular App Architecture With Modules
/Preview Our New Course on Angular Material
/Build Your Own CAPTCHA and Contact Form in PHP
/Object-Oriented PHP With Classes and Objects
/Best Practices for ARIA Implementation
/Accessible Apps: Barriers to Access and Getting Started With Accessibility
/Dramatically Speed Up Your React Front-End App Using Lazy Loading
/15 Best Modern JavaScript Admin Templates for React, Angular, and Vue.js
/15 Best Modern JavaScript Admin Templates for React, Angular and Vue.js
/19 Best JavaScript Admin Templates for React, Angular, and Vue.js
/10 Best WordPress Facebook Widgets
13Hands-on With ARIA: Accessibility for eCommerce
/New eBooks Available for Subscribers
/Hands-on With ARIA: Homepage Elements and Standard Navigation
/Site Accessibility: Getting Started With ARIA
/How Secure Are Your JavaScript Open-Source Dependencies?
/New Course: Secure Your WordPress Site With SSL
/Testing Components in React Using Jest and Enzyme
/Testing Components in React Using Jest: The Basics
/15 Best PHP Event Calendar and Booking Scripts
/Create Interactive Gradient Animations Using Granim.js
/How to Build Complex, Large-Scale Vue.js Apps With Vuex
1 /Examples of Dependency Injection in PHP With Symfony Components
/Set Up Routing in PHP Applications Using the Symfony Routing Component
1 /A Beginner’s Guide to Regular Expressions in JavaScript
/Introduction to Popmotion: Custom Animation Scrubber
/Introduction to Popmotion: Pointers and Physics
/New Course: Connect to a Database With Laravel’s Eloquent ORM
/How to Create a Custom Settings Panel in WooCommerce
/Building the DOM faster: speculative parsing, async, defer and preload
1 /20 Useful PHP Scripts Available on CodeCanyon
3 /How to Find and Fix Poor Page Load Times With Raygun
/Introduction to the Stimulus Framework
/Single-Page React Applications With the React-Router and React-Transition-Group Modules
/12 Best Contact Form PHP Scripts
1 /Getting Started With the Mojs Animation Library: The ShapeSwirl and Stagger Modules
/Getting Started With the Mojs Animation Library: The Shape Module
/Getting Started With the Mojs Animation Library: The HTML Module
/Project Management Considerations for Your WordPress Project
/8 Things That Make Jest the Best React Testing Framework
/Creating an Image Editor Using CamanJS: Layers, Blend Modes, and Events
/New Short Course: Code a Front-End App With GraphQL and React
/Creating an Image Editor Using CamanJS: Applying Basic Filters
/Creating an Image Editor Using CamanJS: Creating Custom Filters and Blend Modes
/Modern Web Scraping With BeautifulSoup and Selenium
/Challenge: Create a To-Do List in React
1 /Deploy PHP Web Applications Using Laravel Forge
/Getting Started With the Mojs Animation Library: The Burst Module
/10 Things Men Can Do to Support Women in Tech
/A Gentle Introduction to Higher-Order Components in React: Best Practices
/Challenge: Build a React Component
/A Gentle Introduction to Higher-Order Components in React
/Creating Pretty Popup Messages Using SweetAlert2
/Creating Stylish and Responsive Progress Bars Using ProgressBar.js
/18 Best Contact Form PHP Scripts for 2022
/How to Make a Real-Time Sports Application Using Node.js
/Creating a Blogging App Using Angular & MongoDB: Delete Post
/Set Up an OAuth2 Server Using Passport in Laravel
/Creating a Blogging App Using Angular & MongoDB: Edit Post
/Creating a Blogging App Using Angular & MongoDB: Add Post
/Creating a Blogging App Using Angular & MongoDB: Show Post
/Creating a Blogging App Using Angular & MongoDB: Home
/Creating a Blogging App Using Angular & MongoDB: Login
/Creating Your First Angular App: Implement Routing
/Persisted WordPress Admin Notices: Part 4
/Creating Your First Angular App: Components, Part 2
/How Laravel Broadcasting Works
/Persisted WordPress Admin Notices: Part 2
/Create Your First Angular App: Storing and Accessing Data
/Persisted WordPress Admin Notices: Part 1
/Error and Performance Monitoring for Web & Mobile Apps Using Raygun
/Using Luxon for Date and Time in JavaScript
7 /How to Create an Audio Oscillator With the Web Audio API
/How to Cache Using Redis in Django Applications
/20 Essential WordPress Utilities to Manage Your Site
/Introduction to API Calls With React and Axios
/Beginner’s Guide to Angular 4: HTTP
/Rapid Web Deployment for Laravel With GitHub, Linode, and RunCloud.io
/Beginners Guide to Angular 4: Routing
/Beginner’s Guide to Angular 4: Services
/Beginner’s Guide to Angular 4: Components
/Creating a Drop-Down Menu for Mobile Pages
/Introduction to Forms in Angular 4: Writing Custom Form Validators
/10 Best WordPress Booking & Reservation Plugins
/Getting Started With Redux: Connecting Redux With React
/Getting Started With Redux: Learn by Example
/Getting Started With Redux: Why Redux?
/Understanding Recursion With JavaScript
/How to Auto Update WordPress Salts
/How to Download Files in Python
/Eloquent Mutators and Accessors in Laravel
1 /10 Best HTML5 Sliders for Images and Text
/Site Authentication in Node.js: User Signup
/Creating a Task Manager App Using Ionic: Part 1
/Introduction to Forms in Angular 4: Template-Driven Forms
/24 Essential WordPress Utilities to Manage Your Site
/25 Essential WordPress Utilities to Manage Your Site
/Get Rid of Bugs Quickly Using BugReplay
1 /Manipulating HTML5 Canvas Using Konva: Part 1, Getting Started
/10 Must-See Easy Digital Downloads Extensions for Your WordPress Site
/22 Best WordPress Booking and Reservation Plugins
/Understanding ExpressJS Routing
/15 Best WordPress Star Rating Plugins
/Creating Your First Angular App: Basics
/Inheritance and Extending Objects With JavaScript
/Introduction to the CSS Grid Layout With Examples
1Performant Animations Using KUTE.js: Part 5, Easing Functions and Attributes
/Performant Animations Using KUTE.js: Part 4, Animating Text
/Performant Animations Using KUTE.js: Part 3, Animating SVG
/New Course: Code a Quiz App With Vue.js
/Performant Animations Using KUTE.js: Part 2, Animating CSS Properties
/Performant Animations Using KUTE.js: Part 1, Getting Started
/10 Best Responsive HTML5 Sliders for Images and Text (Plus 3 Free Options)
/Single-Page Applications With ngRoute and ngAnimate in AngularJS
/Deferring Tasks in Laravel Using Queues
/Site Authentication in Node.js: User Signup and Login
/Working With Tables in React, Part Two
/Working With Tables in React, Part One
/How to Set Up a Scalable, E-Commerce-Ready WordPress Site Using ClusterCS
/New Course on WordPress Conditional Tags
/Building With Vue.js 2 and Firebase
6 /Best Unique Bootstrap JavaScript Plugins
/Essential JavaScript Libraries and Frameworks You Should Know About
/Vue.js Crash Course: Create a Simple Blog Using Vue.js
/Build a React App With a Laravel RESTful Back End: Part 1, Laravel 5.5 API
/API Authentication With Node.js
/Beginner’s Guide to Angular: Routing
/Beginners Guide to Angular: Routing
/Beginner’s Guide to Angular: Services
/Beginner’s Guide to Angular: Components
/How to Create a Custom Authentication Guard in Laravel
/Learn Computer Science With JavaScript: Part 3, Loops
/Build Web Applications Using Node.js
/Learn Computer Science With JavaScript: Part 4, Functions
/Learn Computer Science With JavaScript: Part 2, Conditionals
/Learn Computer Science With JavaScript: Part 1, The Basics
/Create Interactive Charts Using Plotly.js, Part 5: Pie and Gauge Charts
/Create Interactive Charts Using Plotly.js, Part 4: Bubble and Dot Charts
/Create Interactive Charts Using Plotly.js, Part 3: Bar Charts
/Awesome JavaScript Libraries and Frameworks You Should Know About
/Create Interactive Charts Using Plotly.js, Part 2: Line Charts
/Bulk Import a CSV File Into MongoDB Using Mongoose With Node.js
/Build a To-Do API With Node, Express, and MongoDB
/Getting Started With End-to-End Testing in Angular Using Protractor
/TypeScript for Beginners, Part 4: Classes
/Object-Oriented Programming With JavaScript
/10 Best Affiliate WooCommerce Plugins Compared
/Stateful vs. Stateless Functional Components in React
/Make Your JavaScript Code Robust With Flow
/Build a To-Do API With Node and Restify
/Testing Components in Angular Using Jasmine: Part 2, Services
/Testing Components in Angular Using Jasmine: Part 1
/Creating a Blogging App Using React, Part 6: Tags
/React Crash Course for Beginners, Part 3
/React Crash Course for Beginners, Part 2
/React Crash Course for Beginners, Part 1
/Set Up a React Environment, Part 4
1 /Set Up a React Environment, Part 3
/New Course: Get Started With Phoenix
/Set Up a React Environment, Part 2
/Set Up a React Environment, Part 1
/Command Line Basics and Useful Tricks With the Terminal
/Build a React App With a Laravel Back End: Part 2, React
/Build a React App With a Laravel RESTful Back End: Part 1, Laravel 9 API
/Creating a Blogging App Using React, Part 5: Profile Page
/Pagination in CodeIgniter: The Complete Guide
/JavaScript-Based Animations Using Anime.js, Part 4: Callbacks, Easings, and SVG
JavaScript-Based Animations Using Anime.js, Part 3: Values, Timeline, and Playback
10 Elegant CSS Pricing Tables for Your Latest Web Project
/Getting Started With the Flux Architecture in React
/Getting Started With Matter.js: The Composites and Composite Modules
/Getting Started With Matter.js: The Engine and World Modules
/10 More Popular HTML5 Projects for You to Use and Study
/Understand the Basics of Laravel Middleware
/Iterating Fast With Django & Heroku
/Creating a Blogging App Using React, Part 4: Update & Delete Posts
/Creating a jQuery Plugin for Long Shadow Design
/How to Register & Use Laravel Service Providers
2 /Unit Testing in React: Shallow vs. Static Testing
/Creating a Blogging App Using React, Part 3: Add & Display Post
/Creating a Blogging App Using React, Part 2: User Sign-Up
20 /Creating a Blogging App Using React, Part 1: User Sign-In
/9 More Popular HTML5 Projects for You to Use and Study
/Creating a Grocery List Manager Using Angular, Part 2: Managing Items
/9 Elegant CSS Pricing Tables for Your Latest Web Project
/Dynamic Page Templates in WordPress, Part 3
/Angular vs. React: 7 Key Features Compared
/Creating a Grocery List Manager Using Angular, Part 1: Add & Display Items
New eBooks Available for Subscribers in June 2017
/Create Interactive Charts Using Plotly.js, Part 1: Getting Started
/The 5 Best IDEs for WordPress Development (And Why)
/33 Popular WordPress User Interface Elements
/New Course: How to Hack Your Own App
/How to Install Yii on Windows or a Mac
/How to Register and Use Laravel Service Providers
/
waly Good blog post. I absolutely love this…