Angular Tutorial for Beginners: Learn Angular & TypeScript

4.53M views19030 WordsCopy TextShare
Programming with Mosh
Angular tutorial for beginners: Learn Angular & TypeScript from scratch. 🚀 Ready to master Angula...
Video Transcript:
hi my name is Muhammad Ali and I'm going to be instructor over the next few hours in this course you're going to learn everything about angular from the basic to the advanced topics and you will build and deploy a real ecommerce application using angular firebase and the new awesome bootstrap for let me show you a demo of this application real quick we're gonna build an e-commerce application for an imaginary organic shop so here on the home page we have master detail you can select the category and see all the products in that category you can
add a product or a shopping cart change the quantity and the number of items in a shopping cart it's updated in real time and here's our shopping cart again here we can change the quantity for each item and the total price as well as the total number of items in the shopping cart get updated immediately if I open another tab and add another product to our shopping cart what we have on the shopping cart tab gets updated automatically without me having to refresh the page so all the data we show to the user is in
sync everywhere in the application and this is the beauty of a real-time application now let's check out here we have a shipping form and the summary of all the products in our shopping cart and again this summary gets updated as soon as I make a change or a shopping cart in another tab once we place this order it will be visible to our admins so I'm an admin user and I have this menu here manage orders here we can see all the orders in the application other users will not see this page here so here
we have authentication and authorization as an admin I can also manage the products so here we have all the crud operations we can quickly search for a product you can sort the data resize the columns or navigate to a different page these are the patterns that you see in a lot of real-world applications and in this course you're going to learn how to implement these patterns in your applications so are you excited to learn angular and build this application then let's jump in and get started so in case you're an absolute beginner with angular let
me quickly explain in two minutes what angular is and why you should learn it angular is a framework for building client applications in HTML CSS and either JavaScript or a language like typescript that compiles to JavaScript a typescript is more common in the angular community because angular itself has been written with typescript now if you have never worked with typescript before don't worry at all it's very easy and you're gonna get familiar with it in this course now one question that a lot of beginners have is why do we need angular can we not use
plain old JavaScript or jQuery we certainly can and that's how a lot of web applications out there are built but as our applications get more complex vanilla JavaScript or jQuery code becomes hard to maintain we need a way to properly structure our application sure there are JavaScript patterns out there that help us with the structuring but these patterns are hard to understand for a lot of beginners to JavaScript plus a lot of applications built with vanilla JavaScript or jQuery are hard to test and that's why over the past few years various frameworks have been built
and evolved to make web application development easier angular is an example of such frameworks it gives our applications a clean and loosely coupled structure that is easy to understand and easy to maintain it also brings in a lot of utility code that we can reuse in various applications especially when dealing with the users navigation and the browser history plus applications built with angular are more testable so we can easily write automated tests to test various parts of our application as I will show you later in the course so to answer this question no you don't
need a framework like angular to build client applications but using angular makes your life a lot easier all right now that you know what angular is let's take a look at the architecture of angular applications a lot of modern applications have at least two parts a front end and a back end the front end also called the client is the part that runs in a web browser and this is what the user sees and interacts with so it essentially includes the user interface or UI of an application we use HTML CSS typescript and angular to
build the front end the back end sits on a web server or multiple web servers in the cloud and is responsible for storing the data and doing any kind of processing our front end or the client app talks to the back end to get or save the data one of the questions that a lot of beginners ask me is maash how do I save my data in angular well you don't in most cases you don't save the data on the client because it can easily disappear as the user clears the browser data or moves to
a different computer that's why we store the data on the server so here we often have one or more databases as well as a bunch of HTTP services or api's to make this data available to the clients in case you don't know API stands for application programming interface now if you put this fancy name aside these HTTP services or AP eyes are essentially endpoints that are accessible via the HTTP protocol so we can call them using simple HTTP requests to get or to save the data if that's too much technical jargon here let me give
you a metaphor think of a port where ships load or unload these are points to get loads in and out of a town right now imagine these ports are HTTP endpoints ships are HTTP requests and loads are data so just like we can send a ship to a port to get some load and bring to us a client app sends an HTTP request to an endpoint to get some data so this is how the big picture works our web applications have a front end and a back end on the back end we have one or
more databases and API is that make the data available to the clients for a larger application around a complex domain this is where we implement the business logic of the application like calculating the tax and shipping cost based on various parameters the front end or the client on the other hand is all about the presentation so here we have our HTML templates as well as the presentation logic of our application this logic is all about displaying data and responding to user actions like what should happen when the user clicks on a button or navigates away
from a page these are examples of the presentation logic or the logic that is all about the presentation aspect of an application now in terms of the implementation building the backend requires familiarity with other languages and frameworks and it's completely outside the scope of building client apps with angular so as an angular or a front-end developer you don't have to worry about this this is the job of a back-end developer or a full stack developer who knows both the front end and the back end so for the purpose of this course we're gonna focus on
the front end and if you want to learn about the backend development you can always pick up a course later down the road but for now let's just focus on one thing and do it well all right in this lecture I'm gonna show you how to set up your development environment and create your first angular project so the first thing you need to install is the latest version of node in case you have never worked with node before it's basically a runtime environment for executing JavaScript code outside the browser in this course we're not gonna
work with node but note provides some tools that we need to build angular projects so if you have an installed node head over to node.js org on this page you can see the latest version of node for your operating system so here the latest stable version is 6.11 and the latest version is version 8 now this latest version has more features but it's not quite stable yet so go ahead and install the latest stable version when you do that open up the terminal on Mac or command prompt on Windows and type node - - version
so you can see on my machine I'm running node version 6 point the minimum version required for building angular applications is version 6.9 once you have node then we're gonna use a tool called node package manager or NPM to install third-party libraries one of these libraries we're going to install in this lecture is angular CLI which stands for command-line interface so it's a command-line tool that we use to create a new angular project or generate some boilerplate code as well as create deployable packages so once again in the terminal we run NPM install - G
which stands for global and finally the name of the package which is at angular slash CLI if you don't put dash G here angular CLI will be installed only in the current folder and it's not going to be accessible anywhere else now if you're on Mac you need to put sudo at the beginning of this command to execute it as an administrator all right next we need to enter our password this process is going to take a little while all right beautiful we installed angular CLI now to ensure that the installation was successful we can
type ng - - version so you can see I'm writing angular CLI version one point one point zero and below that you can see the version of node on my machine once again it's 6.10 so with angular CLI in place now we can create a new angular project so we type ng new and let's call this project hello - world so this generates a bunch of files and folders and then it's going to use NPM to download the third-party libraries alright our project is successfully created now to start coding we need a code editor the
editor I'm gonna use in this course is Visual Studio code or vs code it's a beautiful cross-platform lightweight editor and you can download at code that Visual Studio comm if you don't like this editor feel free to use any editors that you prefer you can use sublime you can use atom or any other editors now if you're going to use vs code I want you to add it to the path so you can easily open it from the terminal so here if you're using Mac press shift command + P or if you're using Windows press
shift ctrl + P this opens up the command palette now here type code look at this command here install code command in path with this we can go to the terminal in the folder where we created a new project hello world simply type code period so this opens up vs code pointing to the current folder now in the next lecture we're going to look at this structure you're gonna learn what files and folders we have here but before we get there let's make sure that this application works so back in the terminal once again we
use angular CLI to load our application in a web server so we type ng space serve so now we have a live development server listening on localhost port 4200 and angular CLI also compile our application it generated bundles for JavaScript and CSS files so we can open up Chrome and head over to localhost port 42 hundred beautiful this is our first angular app next we're going to look at the structure of our new angular project alright now let's see what files and folders we have in this new project so the first folder we have here
is e - e which stands for end to end and this is where we write end-to-end tests for our application if you have not worked with end-to-end tests these are basically automated tests that simulate a real user so we can write code to launch our browser navigate to the home page of our application click a few links here and there fill out a form click a button and then assert that there is something on the page this is an example of an end-to-end test now that's beyond the scope of this course so we don't have
to worry about it yet below that we have node modules and this is where we store all the third-party libraries that our application may depend upon now this folder is purely for development so when we compile our application parts of these third-party libraries are put in a bundle and deployed with our application so we're not going to deploy this node modules folder to a server you're going to see this later in the course below that we have the source folder and this is where we have the actual source code of our application so we have
this app folder here and inside this folder we have a module and a component so every application has at least one module and one component you're going to get familiar with this components and modules very soon below that we have this assets folder where we store the static assets of our application so if you have any image files and it takes files and icons all of these go here below that we have this environments folder and this is where we store configuration settings for different environments so we have one file for the production environment and
the other for the development environment now the other files we have in the source folder are favorite icon which is the icon displayed in the browser we have index dot HTML which is a very simple HTML file that contains our angular application so note that here we don't have any references to a script or a stylesheet these references will be dynamically inserted into his page as I will show you later in the course now below that we have this main file which is a typescript file and this is basically the starting point of our application
so in a lot of programming languages we have this concept of the main method which is the starting point of a program we have the same concept in our angular applications so all we are doing here is bootstrapping the main module of our application which is in this case app module so angular loads this module and everything else starts from there we have this polyfills file which basically imports some scripts that are required for running angular because the angular framework uses features of JavaScript that are not available in the current version of JavaScript supported by
most browsers out there so these polyfills fill the gap between the features of JavaScript and angular needs and the features supported by the current browsers below that we have styles of CSS and this is where we had the global styles for our application and also each page or each component can have its own Styles as you will see later in the course below that we have test the TS which is basically used for sending them our testing environment again for now we don't have to worry about this outside the source folder we have a configuration
file for angular CLI it's pretty standard configuration you don't have to worry about this for the most part below that we have editor config so if you're working in a team environment you want to make sure that all developers in the team use the same settings in their editors so this is where you store your settings we have this get ignore file which is basically for excluding certain files and folders from your git repository if you have not worked with git don't worry it's not something that you need to know in order to build applications
with angular it's basically a tool for managing and versioning your source code now below that we have karma that config the Jas which is a configuration file for karma we is a test runner for javascript code again we're not going to worry about running tests at this stage now below that we have an important file package JSON now this is a standard file that every node project has apart from a bunch of basic settings here like the name and version of your application we have this setting here dependencies which determines the libraries that your application
is dependent upon so here you can see we have nine references to angular libraries all these libraries start with at angular and after that we have the name of the library so the first library here is for animations if you're not going to use animations in your application you can delete this here so in the future as we use third-party libraries you will see them listed here under the dependencies now below that we also have another setting or another key called dev dependencies and these are the libraries that we need in order to develop this
application so we don't need these to run our application on a production server these are purely for a developer machine so here we have a reference to angular CLI which are only too familiar with we also have a few other references to karma which is again a test runner for javascript code now below this package that JSON we have protractor that config the Jas which is basically a tool for running end-to-end tests for angular again we're not gonna worry about it the another file here is TS config which has a bunch of settings for your
typescript compiler so your typescript compiler looks at these settings and based on these settings is going to compile your typescript code into JavaScript that browsers can understand again for the most part you don't have to change any of this here just be aware that if in the future in a complex project you need to change your typescript compiler settings this is where you need to apply your changes and finally we have TS lint like JSON which includes a number of settings for TS linked in case you don't know TS lint is a static analysis tool
for typescript code so it shakes your typescript code for readability maintainability and functionality errors so this is the basic structure of an angular project all right now let's make a tiny change to this application so in the app folder open up app that component the TS now if you have never worked with JavaScript before don't worry about this code as we go through the course I'm gonna break this up for you so you will know exactly what is happening here so all I want you to do here is to change this string from app to
angular app now save the file back in the terminal look at this message webpack compiling so angular CLI uses a tool called web pack which is a build automation tool it gets all our scripts and stylesheets combines them puts them in a bundle and then minify that bundle and this is for optimization so here you can see we have a few bundles like polyfills which includes all the scripts to fill the gap between the version of JavaScript that angular needs and the version of JavaScript supported by most browsers out there we have main bundle which
is all the source code of our application we have styles bundle which includes all our style sheets and note that here style sheets are actually stored in a JavaScript bundle you're gonna see that in a second we also have this vendor bundle which includes all the third-party libraries now at the time of recording this video unfortunately angular CLI does not allow you to customize the name of these bundles or add additional bundles but there is a discussion going on and guess how chances are this may change in the future now that aside what I want
you to note here is that whenever you change one of your files where that file being a stylesheet a typescript file or an HTML file web pack automatically recompile your application and refreshes your bundles so now here at the bottom you can see web pack compiled successfully now if you go back to the browser look without me even refreshing this page now we have the new title welcome to an angular app so this is a feature of web pack called hot module replacement or hot module reloading so whenever one of the source files is modified
web pack automatically refreshes your browser now let's right-click on this page and go to view page source at the bottom of this page look at these script tags so all the bundles that webpack generator it also injected them into our index dot HTML so just to refresh your memory here in index dot HTML look we don't have any references to your style sheet or a script file so this is something that happens at runtime so web pack automatically inject these scripts into our index dot HTML now let's take a look at these Styles that bundle
the js-- so basically what we have here is some JavaScript and in the middle of this JavaScript code you can find the Styles used in your application now how this works is a little bit complicated so don't worry about it for now what I want you to know is that all your style sheets are compiled into a Java Script bundle one question that often comes up is what's the difference between angularjs angular 2 and angular for and how did we jump from angular 2 to angular 4 well angularjs was introduced in 2010 as a JavaScript
framework for building client applications soon it gained popularity an angular team started adding new features to the core but the framework was not designed with the needs of today's applications in mind plus it was overly complex so angular team decided to rewrite the original framework using typescript and as a result angular 2 came out in mid 2016 this new version is entirely different from angular 1 to the extent that you can think of it as a completely different framework now this made a lot of developers unhappy because they had a lot of applications built with
angular 1 with each application over a few thousand lines of code that had to be rewritten but overall I personally like the direction that angular team took and how they've rebuilt angular with typescript this is a much better framework it's a lot cleaner and it's a lot easier to understand and to work with now after a few minor upgrades to angular 2 something strange happened we were up to angular 2.3 and then all of a sudden and your 4 came out so a lot of developers including myself wondered what happened to angular 3 we thought
we made something really big here but unlike angular 2 angular 4 was not a new framework with a lot of breaking changes in fact it wasn't even a major upgrade so let me explain what happened angular consists of a few different libraries that are distributed as separate node packages via NPM for example we have the core library that we use in every application we have angular compiler we have angular HTTP for calling HTTP services we have angular router for adding navigation to applications and a few other libraries now all these libraries were version the same
except the router library in order to align these versions and avoid confusion in the future angular team decided to go straight to an angular version 4 so in a sense angular 4 is not a major upgrade to angular 2 and you can think of it as angular 2.4 as simple as that now after all this confusion in the community about angular versions the team decided to drop the version suffix and simply call the framework angular so now we have two kinds of angular we have angularjs which is the first generation of angular written in JavaScript
and it's going to die sooner or later and we also have angular which refers to angular 2 or later in our discussions in our articles and whenever we want to talk about angular 2 or later we should really use the word angular like I'm gonna angular developer instead of I'm gonna angular 2 developer or I'm an angular 4 developer see it's really weird we should use versions only when we need to talk about a specific release for example when we want to upgrade angular 4 to angular 5 then everybody knows what is the scope of
this upgrade and what are the potential breaking changes that can impact an application so this is all about angular version history right now let me quickly give you an overview of how AB structured this course and how we can get the most out of it in the shortest possible time so in this course we have three parts essentials advanced topics and the final project we're going to start the essential part with an introduction to typescript and an object-oriented programming this will prepare you to build angular applications so then we'll look at angular fundamentals displaying data
and handling events components directives template driven forms reactive forms consuming HTTP services routing and navigation authentication and authorization deployment and building real-time applications with firebase so these are the essentials that you will use frequently in real-world applications then we get into the territory of the advanced topics and my advanced I don't mean complicated I mean anything that is beyond the basics so in this part of the course I will cover animations angular material redux architecture unit testing and integration testing and over the last part we'll build that ecommerce application that I showed you at the
beginning of the course this part also includes a few sections and in each section we'll build one module of functionality in this application so here we have sections like product management shopping cart checkout and so on now I understand that you might be busy and not have enough time to watch the entire course and that's perfectly fine so I'm gonna give you a shortcut a shortcut that allows you to get the most out of the course within the shortest possible time start with the essentials watch all these sections in sequence but feel free to skip
the section called reactive forms because we're not going to use the materials in this section in our final project also you can skip consuming HTTP services as well as authentication and authorization you need to watch these sections if you want to be old back-end for your application using frameworks such as a speed add net Express Django and so on but this ecommerce application will build in this course doesn't have a custom built back-end we use firebase as the backend so things are a little bit different here if this sounds confusing to you don't worry I
will clarify it in the section about firebase so here's my suggestion to you watch these sections in the essential part in sequence and then move to the final project part I want you to build this application because that's where you will see all these moving parts coming together plus those sections include tons and tons of tips and techniques that I've shared with you and these are the things I have learned over the past 17 years of working in the industry as a professional software developer they really change your thinking about programming and software engineering I've
worked really hard for these sections and I want you to watch them once you finish the project then you will have a good understanding of the big picture then you can come back and learn about the other sections in the course in isolation depending on your needs for example if you want to learn how to add animations to your applications you can simply go watch the animation section or if you want to learn about reactive forms you can just go back to that section so focus on the absolute essentials and then move to the final
project hi thank you for watching my angular tutorial if you enjoyed this video please like it and share it with others also you can subscribe to my channel for free new videos every week this video is part of my complete angular course with almost 30 hours of high quality content where you learn everything about angular from the basic to the advanced topics all in one course so you don't have to jump from one tutorial to another in case you're interested you can get this course with a big discount using the link in the video description
and if not that's perfectly fine continue watching as the section is coming up in order to build applications with angular you need to be comfortable with type script so in this section I'm going to introduce you to the fundamentals of typescript and object-oriented programming principles so by the end of this section you will have a good understanding of type annotations arrow functions interfaces classes constructors access modifiers properties and modules if you are familiar with this concept and know how to implement them in typescript feel free to skip the section and move on to angular otherwise
you really need to watch every lecture in this section so now let's get started so what is typescript typescript is not an entirely new language it's a superset of JavaScript so that means any valid JavaScript code is also valid typescript code but typescript has additional features that do not exist in the current version of JavaScript supported by most browsers out there for example in typescript we have this concept of strong or static typing if you have worked with languages like C sharp and Java you know that in these languages when we define a variable we
need to specify the type of that variable now in time script typing is optional so we don't have to use this feature but using this feature makes our applications more predictable and it also makes it easier to debug them when something goes wrong typescript also brings quite a few object-oriented features that we have missed in JavaScript for a long time we have the concept of classes interfaces constructors access modifiers like public and private filled properties generics and so on you're going to learn about this in this section another benefit of using typescript is that with
typescript we can catch errors at compile time instead of at runtime well of course not all kinds of errors but a lot of errors so there is a compilation step involved and when we compile our typescript code we can catch these errors and fix them before deploying our application and finally another benefit of using typescript is that we get access to some great tools out there one thing that I personally love about typescript is the intelligence that we get in our code editors again you're gonna see that in this section so typescript is a beautiful
language and it's basically a superset of JavaScript so any valid JavaScript code is also valid typescript code now the browsers out there they don't understand typescript and it's very unlikely that they're going to support it in the future so we need to compile or more accurately transpile our typescript code into JavaScript so this is part of building our application whenever we build our application typescript compiler kicks in and it transpires our typescript code into JavaScript code that browsers can understand now that's enough introduction next I'm going to show you how to install typescript and write
your first typescript program in this lecture I'm gonna show you how to install time script and write your first typescript program so here we are in the terminal we're not gonna work with angular in this section we're gonna purely focus on typescript so first we need to install typescript globally on our machine so npm install - g which stands for global typescript and of course if you're on Mac get me to put sudo at the front all right beautiful so I've installed the latest version of typescript which is currently version 2.3.4 now we can type
TS C which stands for typescript compiler - - version again you can see that I'm running type scribe 2.3.4 alright now I'm going to create a new folder for this section so let's call this TS hello let's go to this folder now here I'm gonna create a new file and open it with vs code so code main TS so now I'm gonna write some plain JavaScript code and I want to show you that all this JavaScript code is also valid typescript code so first I'm going to define a function let's call this log that takes
a message and here we simply log that message on the console like this then I'm gonna declare a global variable let's call this message and set it to this string hello world and finally call our log function message so this is just plain JavaScript code right now save back in the terminal we need to transpile this type script file into JavaScript so TSC or typescript compiler may not yes not if you look at the files in this folder look we have main degeus and main dirty s now this transpilation or a compilation step when you're
building an angular app happens under the hood so you don't have to manually call the typescript compiler in fact when you've run your application using ng serve angular CLI calls typescript compiler under the hood to transpile all our typescript code alright now let's open our main the J's file so code main is so it's exactly the same code that we wrote but now it's in JavaScript file so all JavaScript code is also valid typescript code now back in the terminal I can execute this code using node so node main is and we got the hello
world message on the console so from the next lecture we're going to look at specific features of typescript that we don't currently have in JavaScript all right let's explore typescript by looking at variable declarations so in typescript there are two ways to declare a variable we can use the VAR keyword which you have seen in JavaScript like var number we set it to 1 or we can use the let keyword so let count to be 2 now before I explain the difference I need to clarify that the let keyword is also being added to the
JavaScript so JavaScript has a few different versions we have es5 or a chemo script 5 which is the version of JavaScript supported by pretty much all browsers out there it's been around for a long time now we have es6 which is a newer version and it was introduced in year 2015 and from that point the ECMO script team which is the team extending Java Script decided to use the year number instead of the version number so we have a common script 2015 2016 and 2017 now in ECMO script 2015 which is basically es6 we also
have this LED keyword but in case you are not familiar with it let me explain how it works so I'm going to define a function let's call it do something it doesn't really matter now here I'm gonna define a for block so var we said I to 0 and as long as I is less than 5 let's increment it here we have a block and then log it on the console now finally at the end of this function I'm gonna log this eye one more time but with the label finally and then I'm gonna call
this function here so in the terminal I'm gonna compile this file main that TS and also at the same time run it with node main is note that the value of I at the end is 5 so this is the issue we have when declaring a variable using the VAR keyword so we have declared I here inside this for block but it's also meaningful and available outside the for block now if worked with languages like C sharp or Java you know that we don't have this concept in those languages in JavaScript a variable declared with
the VAR keyword is scoped to the nearest function so in this case the nearest function is do something so once we declare I inside this for block it's available anywhere in this function now let's see what happens when we declare this variable using the let keyword so let now look we immediately got and red underline here which indicates a compilation error this is one of the beauties of typescript when you're a writing typescript code you can catch these errors at compile time before you run your application before you deploy it now let's hover our mouse
here so this is the error cannot find name I so now I is scoped to the nearest block instead of nearest function and this is the proper way to declare variables which prevents a lot of issues later down the road now I want to clarify something let me see you again Spile back in the terminal first I'm gonna remove main Jas now I'm gonna recompile our main des TS okay we got our error here cannot find name I however if you look at the files in this folder we do have main the GS so even
though we have a compilation error the typescript compiler still generated main dejay s let's have a look at the content of this file so this is the code that is generated so by default typescript compiler compiles our typescript code to es 5 or X my script 5 which is the older version of JavaScript that is supported by all browsers out there now there we don't have the lead keyword so that's why our compiled code now uses the VAR keyword and this is perfectly valid JavaScript code so I can go into terminal and simply run this
code and get the same output as before so what I want to clarify here is the typescript compiler reports these errors but still generate valid scrape coat so here's a takeaway for this lecture from now on anywhere we want to declare a variable we use the lead keyword once again this does not stop the compilation step but at least we can catch the issues earlier during the compile time next we're going to look at different types we have and in typescript in this lecture I'm gonna show you different types we have in typescript so let
me start by declaring a variable called count and set it to 5 now if I set this to let's say a character or a string like a note that I immediately get a compilation error here telling me that this a string or a character is not assignable to type number now we can perfectly do this in JavaScript because in JavaScript we can change the type of variables on the fly but in typescript we get a compilation error now once again I want to clarify that we can perfectly compile this using typescript compiler and we will
get valid JavaScript code so if I go to terminal and type typescript compiler main the TS now look this is our main de Jas so we have this count variable and we have changed its value we can perfectly execute this no problem however code like this is very likely that it's going to break at some point in the future because chances are we're gonna use this count variable inside a four-block so our program is gonna break at runtime we don't want this to happen right that's one of the reasons it's better to write the same
code in typescript so at least we can get a warning during the compilation step now if you hover your mouse over this count variable look at the tooltip you can see a colon and number after a discount so this indicates the type of count variable in our program so here typescript compiler infer that the type of this variable should be a number because we set it to number 5 now what if I declare a variable without initializing it let's look at its type its type is now any and that's exactly like the variables with declare
in JavaScript so I can set a to one then I can change the value to true and then set it to your string even typescript doesn't complain about this so what's the solution if we don't know the value of a variable ahead of time that's when we use type annotations so here we add : and after that we set the type of this variable like number and then look on the third and fourth lines we got compilation errors now in typescript we have a few different types so we have number which can include any integer
or floating-point numbers we have boolean s-- which can be true or false we have strings we have any that you saw earlier we have array so let's say we want to declare an array of numbers we would use a number with square brackets now we can optionally initialize this to an array like this or we can declare an any array and with this we can set this to an array with these values one true a and false of course it's not a good practice we want to avoid this but I'm telling you what is possible
with typescript now we also have another type that I absolutely love and that's inna so let's say we are working with a group of related constants like colours so in plain old or vanilla JavaScript we would define constant colours like this so color red we can set this to zero constant color green we set this to one and constant color blue set it to two now this is a little bit verbose in a lot of object-oriented languages we have this concept called enum so we can put all these related constants in a container so in
typescript we can declare an enum like this enum all lowercase we give you the name like color now curly braces and here we set the values so red green and blue then we can declare a variable like background color and set it to color dot now look we have intellisense here so this tooltip you see here allows us to complete this code without remembering all the details this is one of the things I love about typescript so let's set the background color to color dot red now in terms of the values the first element here
automatically gets the value of zero and each subsequent element gets an incremented value so we don't have to explicitly set these but as a best practice it's better to do so because chances are sometime in the future someone may come here and add a new color here like purple and then purple would automatically become two and the value of blue would change to three so this may break parts of our application so let me revert this by explicitly setting the values if somebody adds a new color here like purple then it will not change the
value of blue now let me show you something let's compile this code and see how we get enum in JavaScript so at a script compiler main TS look at this piece of code here this is how we can implement the concept of enums in JavaScript we can see it's very complicated now compare this with how we declare it an enum here it's much cleaner so the more you work with typescript the more you're gonna love this language in this lecture I'm going to show you the concept of type assertions in typescript so I'm gonna start
by declaring a variable like message and sitting into your string now here we can type message dot I look we get this beautiful intellisense and in this tooltip we can see all the things we can do with a string so all these items with this purple icons are functions for example we have this function called ends with we can call this and see if this message and let's say we'd see and this returns a boolean so we can store the result in another variable like ends with C however sometimes typescript may be a little bit
confused about the type of a variable for example I'm gonna remove this initialization here and initialize this variable on the second line ABC now look at the type of this message variable it's any because by default when we don't set a value the type is any now the problem here is that if I delete this and type period look we don't get that intellisense anymore because ends waste is something that we can do with a string not with an object of type any so what should we do in this case we need to explicitly tell
typescript compiler that this message variable is actually a string and this is what we call type assertions now how do we do type assertions there are two ways one way is to prefix this variable with angle brackets and here we put the type like string now we need to enclose both these parts in parenthesis like this then if you press period we get our beautiful intellisense with all the functions or methods available on string objects now there is also another way to do type assertion so let's change the name of this variable to alternative way
and here instead of angle brackets u.s. message as string they're exactly the same the approach to shoes is purely your personal preference but the first approach is what you see more in a lot of tutorials and code bases out there I just want to clarify something here this type assertion does not change the type of this variable at runtime in fact it's not going to restructure that object in memory it's purely a way to tell typescript compiler about the type of a variable so we can access the intellisense another concept you need to know when
using typescript to build angular applications is the concept of arrow functions so in JavaScript we can declare a function like this let log we set this to a function this function takes a message object and simply logs it on the console like this now in time script there is a shorter way to define this function so let's call the other one do log now we don't need the function keyword anymore we can simply add the parameters in this case message then we add this arrow and that's why we call this an arrow function and finally
the code block so console dot log message now if our function has only one line we can even exclude these curly braces so we can make this code a little bit shorter and cleaner like this if I worked with c-sharp we have seen this before and c-sharp we call this a lambda expression in typescript we call it an arrow function it's exactly the same thing now if you have one parameter here you can even exclude the parentheses but I personally don't like this because I think it makes the code a little bit less readable so
I always like to put my parentheses here to indicate to the reader of this code that these are the parameters now what if you don't have any parameters we just add empty parentheses and of course here you don't have the message so if you have not seen this before get used to it it's a really nice and clean way to define functions all right now let's see how we can use custom types in typescript so I'm gonna start by declaring a function like draw point so this function takes an x and a y and simply
draws it on the screen now we don't want to worry about the actual drawing algorithm we just want to focus on the signature of this function now this function is not too bad here we have only two parameters but sometimes when working with more complex concepts we may end up with a function that has so many parameters like this this is really really bad and it's something you should avoid at all times in those situations it's very likely that a group of these parameters maybe all of them belong to a single concept as an example
think of a car a car has so many different properties we don't want to pass all those properties to a function like drive car instead you want to encapsulate them inside an object and only pass that one object here so in this example instead of passing x and y here it's better to pass a point object and then we can call this function like this draw a point we give it an object with two properties x and y so now our function has a cleaner syntax however there is a problem with this implementation instead of
a point object I can pass a person object that has a name property I know where here we are getting a compile time error but we know that this code is gonna break at runtime because the algorithm in our drop point function is expecting x and y properties so what's the solution well let me revert this back okay we've got x and y so there are two solutions to solve this problem one way is to use what we call inline annotation so just like we can annotate this parameter with the type like number we can
annotate it with a custom type or a custom object so here we add curly braces to indicate an object this object is going to have a property called X which is a number and also another property called Y which is again a number so this is what we call inline annotation it works fine for simple cases but the problem with this as you can see is that this is a little bit verbose also chances are somewhere else we might have another function that expects a point object we don't want to repeat this object literal in
multiple places so in those cases a better approach is to use an interface if you worked with object-oriented programming languages like C sharp and Java you know the concept of interfaces we have the same concept in typescript now if you have never worked with interfaces let me show you how they work so on the top I define an interface and I'm gonna call this point curly braces then I add X is a number and Y is a number so with this interface I'm defining the shape of an object and then I can simplify this declaration
and set the type of this parameter to point this is much cleaner and we can also reuse this in multiple places just one thing note the naming convention I have used here so because I'm introducing a custom type I've used Pascal naming convention so the first letter of every word in the name of the interface should be capitalized so here we have our per case P not a lowercase P okay so when using interfaces always use Pascal naming convention so in the last lecture we use an interface to define the shape of a point object
but there is a problem with this implementation in object-oriented programming languages we have this concept called cohesion which basically means things that are related should be part of one unit they should go together this is what we call cohesion now back to this example on the top we have used an interface to define the shape of a point object and below that we have a standalone function and this is where we have violated the cohesion principle so the concept of drawing a point is highly related to the structure of a point it should not be
a separate function now if you're going to build a utility library for working with points chances are you're going to create another function like get distance that calculates the distance between two points so point a of type point and point B of type point and this goes to is code block again we have violated the cohesion principle we have two functions hanging in the air separate from the point object since these concepts are highly related they should be part of one unit in object-oriented languages we call that unit a class so a class groups properties
and functions that are highly related now in this implementation unfortunately we cannot move these two functions inside our interface because interfaces are purely for declarations they cannot include an implementation in other words we cannot have the algorithm for calculating the distance between two points or drawing a point inside this interface what we can do instead is to add a function here a function declaration so we're gonna have a draw function that takes no parameters and returns void which means it doesn't return anything now you might be asking why don't we have this point parameter here
because if all these members X Y and draw are part of one unit we don't need to pass x and y as parameters to the draw function this function can directly access these properties x and y in the same unit so we don't need this parameter here now in interfaces as I said we cannot have implementation we can only have the signature of a function so with this interface we are telling typescript compiler that our point objects should have two properties x and y and a function called draw the implementation of that is somewhere else
so what should we do now to apply the cohesion principle here we need to use a class instead of an interface so on the top I'm gonna change the type to class and here I'm gonna replace is comma with semicolon so our point class has three members the first two members are what we call fields that we use for storing data and the third member is a function now here in this class we can have the actual implementation of this draw function so we can simply define it like this draw and then add all that
logic for drawing a point now similarly we can have another function get distance that returns the distance between this point and another point like this again all that logic will end up here now with this restructuring you can see that everything about a point is in one unit in one class so we have the coordinate which includes x and y and two functions draw and get distance now in object-oriented programming terms we refer to these members as fields and to these functions as methods so when a function is part of a class we call it
a method alright now with this new implementation you don't want these two functions hanging in the air so delete this is a much better structure also you're not gonna call draw a point like this anymore so here's our point class in the next lecture I'm gonna show you how to create an object of this type and call the draw method you all right so here's our class now let's declare a variable of this type so let point be of type point and then we can type point dot look we have this beautiful intellisense we have
two methods draw and get distance and two fields x and y now in time script we also have a concept called property which is different from a field but a lot of people use these terms interchangeably later in this section you're gonna learn the difference between fields and properties now if you wanna call the draw method simply call it like this so this draw method is now part of the concept of a point it's not a function hanging in the air polluting the global namespace now for this demo I'm gonna add a simple console dot
log here and display the coordinate at this point so X now here I want to add the X field what we cannot use it like this we need to prefix it with this dot so that refers to this field in this class and then I'm gonna add Y is once again this dot Y now let us compile and run this program and see what happens so TSC what should we type here main the TS and we can shortcut by adding this pipe here type node and then main ajs okay you got a runtime error cannot
read property draw of undefined so this is the problem when we call this draw method this point object was undefined because here unlike the basic types we have in typescript like numbers strings billions we're dealing with a custom type when defining an object of a custom type we need to explicitly allocate memory to it how do we do that well here where we declare the point object or the point variable we initialize it using the new operator so this object is a new point and here we add parentheses this is the syntax now you can
see that we have repeated this point here twice so we can make this code a little bit cleaner by removing this type annotation because typescript compiler can infer from this assignment here that the type of this object is a point object and let's verify that so look you're working with a point object now one more time save so back in the terminal typescript compiler main the TS and then note main that is okay we didn't get an error but you can see that these x and y fields don't have a value because by default they
are undefined so we can get back here and set point that x to let's say 1 and point out y - 2 now back in the terminal typescript compiler main dot TS i actually made a mistake earlier so instead of this pipe operator we need to use double ampersand on Mac I don't know the Windows equivalent so with this we can combine multiple comments so note main that is all right beautiful X is 1 and Y is 2 so this is how we use the classes that we define in our programs that one highlight something
here this point here is a class but this point here is an object an object is an instance of a class as a metaphor think of the concept of a human human could be a class but when we create instances of this class like John Bob Mary these are all objects so that's the difference between a class and an object next we're gonna look at constructors all right so I've simplified the code from the last lecture I simply remove the method get distance because we're not going to use it later in this section so here
on the top we define a point class and then below that we initialize a point object now this code is a little bit verbose because we have three lines to create a point object and put it in a valid State what if this point object had a few other properties that we had to initialize like this and maybe a few more here is there a cleaner way absolutely so let me delete this first all right in object-oriented programming languages we have this concept called constructor so every class can have a constructor which is basically a
method that is called when we create an instance of that class so let me show you how it works in the class I'm gonna add a method the name of this method is constructor this is a reserved keyword in typescript now this method can have parameters so X which is a number and Y which is also a number and then here in this method we can initialize these fields so what should be right here this dot X we set it to this X argument that we get here and similarly this that Y we set it
to Y now look we got a compilation error here because when creating a new point object we need to supply these values look at the error supplied parameters do not match any signature of call target so here we need to supply the values for X and y1 and to and with this we can simplify this code and get rid of these two extra lines and here's the end result now what if somewhere else in our program we don't know the initial coordinate of a point in other words what if I want to create a point
object without setting these values is that possible yes absolutely but it's a little bit different from how you have seen that in other languages like C sharp and Java in c-sharp we can have multiple constructors in typescript we can't so the solution for this is to make these parameters optional so here after X I add a question mark and that makes X optional and similarly Y should be optional as well because once you make it parameter optional all the other parameters on the right side of that parameter should also be optional this is a rule
by typescript and a lot of other programming languages so now look we don't have a compilation error when creating a point object without initial values all right so here I've created a point object with an initial coordinate now what do you thin our program you want to have this rule such that when we initialize a point object we should not be able to change the X or Y values with this implementation I can always come here and set point that X to a different value how can we avoid this sometimes we need this feature in
our programs because it will make them more predictable it reduces the chance for bugs so how should we prevent the coordinate of this point object to change after it's initialized well in object-oriented languages we have this concept called access modifiers an access modifier is basically a keyword that we can apply to a member of a class to control its access from the outside so in typescript we have three access modifiers public private and protected public and private are the most common and by default all members are public let me show you what I mean so
here in our point class we have three members right we have two fields and one method so let me create a point object and type point dot look these are the members of the class and because they are all public we can access them here and that's why we can see them in the intellisense however i can go here and prefix this field with the private key word now once we create this point object if I type point dot look X is not in the list it's not accessible it's private so if we try to
set point at X 2/3 look we have a compilation error in typescript it says property X is private and only accessible within class point now with this technique I can go here and I applied the private keyword on the Y field as well and now once I initialize a point object I can no longer change is quite innate I can only call the draw method ok so this is why we access modifiers to control access to certain members of a class from the outside you can apply these access modifiers on field properties and methods now
by default if you don't set an access modifier is assumed to be public so here the draw method as you know is public I can also add the public key word here but this is redundant it's just making my code noisy so you don't really need to add this it's better to keep your code short and clean and use the private access modifier only when you need to next I'm gonna show you one of my favorite features of typescript around access modifiers as you write code with typescript you see constructors that follow a pattern like
what you see here so here we have two parameters in our constructor and we use these two parameters to initialize the fields in this class the code looks a little bit redundant this that x equals x and this dot y equals y typescript as a fantastic feature that helps you achieve the same thing with less code so here we can delete these two fields here and in our constructor we can prefix our parameters with an access modifier so here I want to have two private fields x and y i can simply prefix these with the
private keyword like this so typescript compiler will generate these fields for us and also you don't need these ugly repetitive assignments either so if he prefix a constructor parameter with an access modifier with a private or public typescript compiler will generate a field with the exact same name and it would also initialize that field with the value of this argument it's one of my favorite features and you're gonna see that a lot in this course now clarify something before we finish this lecture in this case our fills were private but if they were public we
would use the public key word here so this means when we create a pointer object we can access the X field okay so I'm gonna revert this back to the private all right now this implementation has a tiny problem we can set the initial coordinate of this point and we can also draw it but there is no way for us to read the coordinate so I cannot access point that the X here so display to the user what's the workaround well one simple solution is to define a method like this yet X and here we
simply return this that X because in this class we do have access to all the private members of this class but we cannot access them from the outside okay now here I can always call point that get X to get the x value and display to the user now let's talk about another use case maybe we want to give the user the ability to set the inertial coordinate here but we also want them to be able to change this coordinate later only if they provide a value within a given range what do I mean by
that let me show you I'm gonna define another method here set X now this method is gonna get a value that's the new value for the eggs field let me scroll down now here first we can do some basic validation so if value is less than zero we want to throw an error throw new error value cannot be less than zero otherwise we want to set this well x2 this new value okay now with this implementation we can always change the value of the X field like this point that set X we set it to
a new value now if you have a use case like that in your applications you can use what we call a property so in typescript and in a lot of object-oriented programming languages we have a concept called property which is exactly for this very use case so look at how I can define a property here we start with the keyword which is get or set and then the name of the property which is in this case X and after that we're gonna have parentheses just like a method okay now similarly I'm gonna change this to
set with a space so we have the set keyword and here it's like we have a function and method now what is the difference the difference is that we can use these properties like fields so here I can read X like this dot note the icon of X it's the same icon we have for fields it's not a method anymore so we can read X and we can also set it like this point that eggs we set it to 10 we don't have to call a method like this it's a cleaner syntax okay so this
is what properties are for if you have private fields that you want to give maybe a read-only access to the outside or if you want to give the consumer of your classes the ability to set the values but you want to have some basic validation that's when you use a property now in this case if I want to give only the read-only access to this underlying field I can simply comment out the setter so we call this method a setter and the other method a getter okay I now look at this compilation error we cannot
change the value of x now let's bring this back one last thing before we finish this lecture so here I have used a capital X for the name of my X property in JavaScript and in type scrape we use camel notation to name our field so that's why earlier we define this private field here within camel casing notation camel casing means the first letter of the first word is lowercase and the first letter of every word after is uppercase now what should we do to use camel casing notation for our properties if I name this
the lowercase eggs it clashes with the existing field so let me revert this back a convention we use to solve this problem is to prefix the name of the underlying field with an underline so let's rename this using f2 and prefix it with an underline okay similarly for the Y parameter or the y field I'm also going to use underline Y then we can rename this property from capital X to lowercase X once again we press f2 lowercase X and note that both instances both the getter and the setter are updated now we can work
with this X property exactly the same way use the X field so here's the lesson a property looks like your field from the outside but internally it's really a method in the class well more accurately it's either one method which is a getter or a setter or a combination of a getter and a setter all right I've simplified the definition of the point class I remove the properties so we have a simple constructor and a draw method and we're using this point class below its definition now this is a very simple program with only one
file but the real world application consists of tens or hundreds of files we don't want to write all the code in one file like main the TS so ideally I want to move the definition of this point class somewhere else in a file like point the TS so here in this project I'm gonna add a new file point a TS now back in Maine the TS I'm gonna select all this code cut it and move it to point a TS now in typescript we have this concept called modules now what a module is requires a
little bit more explanation but for now let me give you a simple pragmatic definition in typescript you can think of each file as a module so in this program we can say we have two modules but this is not quite accurate because these files are not modules yet so in point of TS we have defined this class called point but this is not accessible anywhere outside this file so this file defines its own scope in order for us to use this class somewhere else in our program we need to export this to the outside so
we add the export keyword here and now this is visible outside this file now that we're exporting something on top of this file from type scripts point of view this file is a module now we need to go back to our main de TS and import this class so we can use it so back in main the TS look we have a compilation error cannot find name point because we have not imported this into main the TS so on the top right import in curly braces we add the name of the types we want to
import in this case point now if there are multiple types you want to import we separate them using comma okay so we import point from now here we put the name of the module in quotes what is the name of the module it's the relative pass to that module from this file so both these files are in the same folder we can use period slash which refers to the current folder and then point is the name of our module so it's not point that TS look we get a compilation error so the name of our
module is point now we no longer have a compilation error here and we can create an instance of this point class and use it now there is a lot more to talk about when it comes to modularity in typescript but that's all you need to know for now in order to start building applications with angular because in angular framework we have a lot of types that are exported so we need to import these into our typescript files and use them you're gonna see that a lot in this course the only difference is that angular modules
are defined in a different way so we don't add the relative path to this module files because these files are not really part of our application they're somewhere inside node underline modules folder so when it comes to importing types defined in angular we use the library name as the module name for example one of the libraries is at angular slash core okay so here's the lesson in typescript we divide our program into multiple files in each file we export one or more types these types can be classes functions simple variables or objects and wherever we
need to use these types we need to import them first when we have an import or export statement on top of a file that file is a module from type scripts point of view in angular we also have the concept of modules but angular modules are a little bit different they are not about organization of code in different files they are about organization of your application into smaller functional areas you're going to learn about angular modules in the next section I love your enthusiasm for learning angular as I told you before this tutorial is part
of my complete in ela course where you learn everything about angular from the basic to the advanced topics all in one course you seem to be determined enough to learn angular and I'm so excited to see you made it this far so I highly recommend you to click on the link in the video description and enroll in my complete angular course so thank you for watching if you enjoyed this video please like it and share it with others and finally subscribe to my channel for free new videos every week have a great day in this
section we're going to look at the fundamentals of building applications with angular by the end of this section you will have a basic understanding of angular building blocks such as components templates directives and services so now let's get started so now that you have some basic familiarity with angular let's look at the building blocks of angular apps at the heart of every angular app we have one or more components in fact in a real world app we have tens or hundreds of components but what is a component a component encapsulate the data the HTML markup
and the logic for a view which is the area of the screen that the user sees let's look at the real world example imagine we're gonna build a website like udemy so on this page we have a navigation bar a sidebar and an area to display the list of courses now we can think of all this as one view or one component or we can break this view into smaller more maintainable and potentially reusable components like navbar component sidebar component and courses component similarly in courses component we want to display one or more courses potentially
we can break up this component into smaller components and also to take this to the next level each course component can include a rating component now we can reuse this rating component in multiple places in the same app or in an internal different app as you see angular embraces component-based architecture which allows us to work on smaller and more maintainable pieces that can also be reused in different places so once again a component encapsulate the data the HTML markup and the logic for a view which is an area of the screen that the user sees
every application has at least one component which we call app component or route component a real word angular app is essentially a tree of components starting from the app component or the route component now in angular also have another concept called modules a module is a container for a group of related components every angular app has at least one module which we call app module as your application grows you may want to break that module into smaller more maintainable modules so in our udemy example we can potentially have modules like course module which includes all
the components for displaying courses we can potentially have another module like messaging module which includes a bunch of components for the area of the website where you can send private messages to your instructors we can have an instructor module which includes the components for instructors dashboards that you don't see and potentially an admin module which is the area of the udemy website by the udemy staff as an analogy think of a supermarket in a supermarket we have different aisles for different products we have a section for fruits and vegetables we have another section for snacks
another for hardware and so on the bigger the supermarket the more aisles we have in a tiny grocery store we have probably one or two aisles at the most the same applies to our angular apps so if you're building a simple application we have only one module which we call the app module but as our application grows in functionality we may need to break that module into smaller modules with each module responsible for a specific area of our application in that module we have a bunch of related components okay so this is the big picture
as we go through this course you will learn about these building blocks in more detail all right now let's see these components in action there are basically three steps you need to follow in order to use a component first you need to create a component second you need to register that component in a module and third you need to add an element in your HTML markup let me show you what I mean by this so back in our first angular project first of all make sure to run and you serve to serve this application so
now if you head over to local host port 4200 this is what you see beautiful now back in vs coal I'm gonna create a new component so let's open up the file panel here in the source folder under app here I'm gonna add a new file now let's imagine I want to create a component to display the list of courses so look how I named this file courses dot component dot TS this is the convention that we use when building angular applications now if the name of the component has multiple words we separate them using
a hyphen for example if you're building a component called course form it would call this course - form and then dot component TS okay so courses component the TS now here we start by creating a plane type script class so class courses component once again look at the naming convention here I'm using the Pascal naming convention so the first letter of every word should be capital and also by convention we use the suffix component in the name of the class so here's our class in order for angular to see this class first we need to
export it now so far we have only a plain typescript class this is not a component in order to convert this to a component we need to add some metadata to it that angular understands we use a decorator to achieve this in angular we have a decorator called component that we can attach to a class to make the class a component so first we need to import this decorator on the top so import curly braces component from now the name of the library so at angular slash core this is the core library of angular that
you're going to see a lot in this course so here we import the component decorator and then we need to apply it there is tax class now look at the syntax we use add sign component and then call this like a function so this is what we call a decorator function now this function as you see here takes an argument so here we pass an object and in this object we add one or more properties to tell angular how this component works for example one property that we use quite often is selector so selector and
we set this to a CSS selector so in CSS if I want to reference an element like this I use a selector like this if I want to reference an element like a div that has a class called courses my selector would be dot courses right and if I want to reference an element with the ID courses this is my selector just basic CSS okay so here we want to reference an element called courses why because with components we can extend HTML vocabulary so we can define new elements like courses and inside that we will
have the list of courses or in the future we can define a custom elements a custom HTML element called rating and wherever we use that angular will render a rating component ok so let's delete this my selector for this component is courses now the second property we add here is template and that's the HTML markup we want to be rendered for this component now here I want to render something very simple so let's just add an h2 element and call this courses in a real world application our templates can be several lines of code in
that case we can put them in a separate file and I'm gonna show you how that works later in the course so this is a basic component in angular that was the first step the second step is to register this component in a module that currently our application has only one module which we call app module let me show you where that is so back here in the app folder look we have app but module now once again here we have three import statements on the top so nothing special here on the bottom we have
a typescript class called app module and note that this class is decorated with another decorator function called ng module so with this we convert a plane Tasker class to a module from angular point of view now don't worry about all these properties here like declarations import providers and bootstrap you're going to learn about them later in the course what I want you to focus on now is this property declarations and this is where we add all the components that are part of this module so by default when we generate an application we have one component
called app component and you can see that component is part of this module now I'm gonna add our new component here so courses component so whenever I type the name of a class here and press ENTER it automatically imported on top of my file so import courses component from and here's the name of our typescript module so period slash which refers to the current folder and here's the name of the file courses that component I know that here we don't have dot TS in fact if you add that typescript compiler it doesn't like that so
the name of the module is just the name of the file without the extension so if you want to add this plug-in to vs code simply go here and in the extension search box search for auto import so currently I'm using auto import one point to point to simply install it and then you'll have to restart yes code alright so here's our second step now the third step back to our component so this is the selector for this component which means anywhere we have an element like courses angular is going to render the template for
this component inside that element but where are we going to add that element let me show you so back here in the app folder we have this app dot component at HTML this is the external template for our app component let's have a look so all this markup you see here is for rendering the homepage and this is what we get now I want to simplify this I'm gonna get rid of all this markup add a simple h1 call this angular and below that I'm gonna add our custom element courses so when angular sees this
element it's going to render the template of our courses component all right now back in the browser this is our new home page so let's right click this courses element and inspect this so look what we have here we have this h1 and below that we have our courses element and inside this you can see we have the template for our courses component so this is how angular applications work as another example look at this app root element inside the body element where is this app root well I can the source folder look at index
dot HTML so this is the basic template for our application right now inside the body element we have an element called app - root this is a custom element because we don't have an element in HTML called app - root so from angular point of view we should have a component with a selector for this element and that's our app component let's have a look at that so back in the app folder let's look at an app that component at es so here's our root component or app component look at the selector app that's root
so whenever angular sees an element like that it's going to render the template for this component inside that element in this case our template is external so if we have template URL and you can see the name of our template file after component at HTML so that's why inside app - root here we have the template for app component which includes an h1 and the courses element all right let's quickly review what we have done so far so we created this courses component here then we register this in-app module so here in apt of module
we added our component inside the declarations array and then finally use this component in the template for app component so let's create a review after the component at HTML added this courses element here three steps okay now there are two problems with this approach the first problem is that this approach is a little bit tedious there are so many steps so first we had to create this typescript class then we had to import this component decorator on the top and next we had to apply it on this tab script class there is so much boilerplate
code here now the second issue is that if you forget the second step our application is gonna break let me show you what happens so let's go to app dot module I'm gonna delay it this line here now let's see what happens back in the browser we got a blank page so now we need to look at the console tab of Chrome developer tools so right click anywhere on the page inspect so we can see we have two errors here we can see the details of these errors in the console tab so here's the error
courses is not a known element so if you don't register a component in a module angular doesn't know about it and it doesn't know what to do with this courses element because this is not a native HTML element so now let me show you a quicker and more reliable way to create an angular component we need to go back to the terminal but look our terminal is always busy it's serving the application so we either have to open a new terminal window or we can actually open a terminal window inside vs code so back here
if you press ctrl and backtick which is the character before the number 1 on your keyboard look we have a term here and this is much easier to access and going back and forth between different windows so here we can use angular CLI to generate a component so just like how we generated an application with ng new we can also generate a component with this ng so the syntax is like this ng space G which is short for generate and C which is short for component and then the name of the component let's say we
want to create a component called course so of course look at what happened angular CLI created a directory called course and inside this directory added four files a CSS file for storing the style sheets for this component an HTML file for storing the template a spec file which is for writing unit tests for this component and finally a typescript file which is the actual component itself now what is interesting here is that it also updated app dot module and registered this new component let's have a look so we can close this terminal window using the
same shortcut which is control and backtick now we can open the files panel using command + b on mac or control B on windows ok look at after module so look inside the declarations array now we have course component so this way we don't have to remember to come back here and register our new components now before we move on let me just quickly add our courses component that I removed earlier ok now back in the files panel this is the folder for our new component so in this folder we have these four files now
let's take a look at the typescript class it has all the boilerplate code that we wrote earlier plus a little bit more so here we're importing the component decorator and on Innes which is an interface we're going to look at this later in the course we have this component decorator apply to our typescript class we have a selector you have the URL of our template file as well as the URL of our style sheet file so angular CLI saves us a lot of time now as we go through this course I will show you how
you can use this tool to generate other building blocks for your applications so earlier I told you that a component encapsulate the data the logic and the HTML markup for review so in this example in our courses component we have the HTML markup but we don't have any data or any logic so let's extend this example and take it to the next level I want to define a field in this class to hold the title of this page so title I'm going to set this to list of courses now I'm going to display this title
in our template dynamically so I'm gonna remove this hard-coded label here in angular we have this special syntax double curly braces and we use this to render something in our template dynamically so here I can put this title field this expression will be evaluated at runtime and the value of this title field will be placed in our Dom now if the value of this title field changes at some point in the future angular will automatically update the Dom this is one of the beauties of angular framework so here we have this concept of data binding
so your binding our view to have filled in this component whenever the value of that field changes the view is automatically notified and updated all right now let's save the changes back in the browser alright here's our new title beautiful now back here we don't always have to put the name of a field here we can write any simple JavaScript expressions for example I can put a string here title colon and then concatenate this with our title field save look this is our new title here we can also call a method in this class to
get some value for example let me define a method get title and here I'm gonna return this the title now here we can simply call our new method get title like this and we'll get the exact same result there you go list of courses so this special syntax here we call it string interpolation in the next lecture I'm going to show you how to render a list of courses here alright now let's take this example to the next level instead of displaying a simple title field you want to display the list of courses so first
we need a field to hold the list of courses so courses we set this to an array with three items course one course two and course three now this is a simplified example in a real world application instead of simple strings here we would have objects but don't worry we're gonna get there now I want to display these in our template how should we do that first we need to change this single code to the backtick character so delete backtick backtick is the character before number 1 on your keyboard let me change this as well
now the benefit of using the backtick is that we can break up this template into multiple lines and make it more readable so I want to put this h2 here and below that I want to add a ul and a bunch of list item elements like this now we want to repeat this Li for each course now for that we need to use one of the angular building blocks called directive we use directives to manipulate the Dom we can use them to add a Dom element or remove an existing Dom element or change the class
of a Dom element or its style and so on so here we're going to use a special directive called NG for we use it like an attribute in HTML so we set it to a string and here we're gonna write some expression now before going any further we should prefix this attribute with an asterisk this is a special syntax in angular so whenever you are using a directive that modifies the structure of a dumb you should prefix that directive with an asterisk in case you're curious about the reason I have covered it later in the
section about directives so for now just remember whenever you are using a directive that modifies the structure of the Dom by adding or removing an element you need to fix that with an asterisk now here we want to write an expression similar to what we write in for each blocks so let course of courses what does this mean with the lead keyword we are defining a variable so the name of our variable is course this is like a loop variable in JavaScript all is a special keyword and courses is the field in this class that
we are iterating over so when angular sees this expression it's going to iterate over the courses field and in each iteration this course variable will hold the value of one course at a time now inside this list I know you want to display this course so once again we use string interpolation double curly braces and add this course variable here let's look at the result save back in the browser and here we have the list of our courses beautiful now in most real-world applications we get this courses from the server and for that we need
to use another building block of and get a called a service and that's the topic for the next lecture right now we have the list of courses here but in a real world application most of the time we get these courses from the server so instead of hard-coding them here we need to call an HTTP endpoint to get the list of courses now here we have two options one is to add the logic for calling an HTTP service here in this component but there are a couple of problems with this approach the first problem is
that this logic is going to tightly couple this component to that HTTP endpoint now in the future when we want to write unit tests for this class we don't want to be dependent upon a live HTTP endpoint because this is going to make it harder to execute those unit tests so we want to create a fake implementation of an HTTP service so this is the first issue with writing this logic inside this class inside this component it's going to tightly couple this component to that HTTP endpoint the second issue is that maybe somewhere else in
the application we're going to have another page where we display the list of courses maybe it's part of a dashboard maybe somewhere for an admin with this implementation we have to repeat this logic the logic for consuming that HTTP service in multiple places and that's not good and finally the third issue with this implementation is that a component should not include any logic other than the presentation logic that is the logic behind this view what should happen when we click upon when we select an item from a drop-down list and so on details of how
courses are retrieved should be delegated somewhere else in your application so where should we implement that logic in angular we use services for that so we're going to define a separate class which we call a service and there we'll add this logic for getting the list of courses from an HTTP service then we can reuse this class in multiple places so let me show you how to do that here in the app folder I'm gonna add a new file now look at the naming convention courses dot service the TS so the name of our service
is courses and by convention we have the word service in the file name and finally TS when creating a component we use courses does component at TS so note the difference now here once again you want to export a plane type script class so export class courses service so once again by convention we add the word service as a suffix in the class name now when creating components we decorate this class with the component decorator remember component but in angular we don't have a decorator for services so a service is essentially a plane type script
class so delete now here we want to add a method for getting the list of courses get courses for now we don't want to get distracted with the complexity of consuming an HTTP service so let's just return the same array that we had in our component and later I will show you how to consume an HTTP service so back in our component I'm going to select this array here cut back in the service and simply return it from this method now imagine here in this method we have that logic for consuming an HTTP service with
this implementation we can reuse this class we can reuse this logic in multiple places in our application and also this will separate or decouple our component from this logic so back in our component here we are not going to have any logic for consuming an HTTP service and this allows us to unit test this class without dependency upon that HTTP endpoint so while unit testing in this class we can provide a fake implementation of net service now if that's too complicated don't worry about it your testing is something for the future okay now we have
a service we need to use this service in our component how that's the topic for the next lecture okay now we have a service to get the list of courses from the server we need to use this service in this courses component so first we need to add a constructor here constructor because a constructor is where we initialize an object so here we need to create an instance of our courses service something like this let service be new courses service once again I'm using the auto import plug-in so when I press ENTER it automatically adds
the import statement here on the top so I'll import courses service from current folder courses dot service all right now back in the constructor so we have a service and then we can initialize this course is filled like this this that courses we set this to service that get courses let's test the application and make sure everything works up to this point save okay we get the same list beautiful however there is a problem with this implementation the first problem is that by using this new operator here we have tightly coupled this courses component to
the courses service so this is exactly like the problem we had earlier if we implemented the logic for consuming an HTTP service inside this component we wouldn't be able to unit test this class now we put this logic in a different class courses service but because we're directly creating an instance of this class here we're still tightly coupled to that implementation the other issue here is that if in the future we decide to add a parameter to the constructor of course a service we have to come back here and anywhere else in our application where
we have used this courses service and add a new argument like one so any time we change the constructor of this service we end up with multiple changes in our application code so this is very fragile so what should we do well in we creating an instance of the courses service we can ask angular to do that for us so we can delete this line here and add a parameter in this constructor call it service of type courses service with this when anger is going to create an instance or component it looks at this constructor
is that this constructor has a dependency this dependency is of type courses service so first it creates an instance of the courses service and then passes that to this constructor now with this implementation if we change the constructor of courses service and add a new parameter we don't have to modify a hundred places in our code to reflect the change angular will automatically instantiate a new courses service object the second benefit of this implementation is that when we're going to unit test this courses component instead of supplying an actual courses service to this constructor we
can create a fake implementation of this service that doesn't use at HTTP service on the backend in other words we have decoupled our courses component from courses service so here's the lesson when you use the new operator like this inside a class you have tightly coupled your class to that implementation you cannot change this at runtime but when you add that dependency as a parameter of a constructor you have decoupled that class from that dependency now you're not done yet we need to instruct angular to create an instance of course a service and pass it
to our courses component this concept is called dependency injection so we should instruct angular to inject the dependencies of this component into its constructor as simple as that that's dependency injection a lot of people think dependency injection is so complicated but it's really a $25 term for a five-cent concept so dependency injection means injecting or providing the dependencies of a class into its constructor now angular has a dependency injection framework built into it so when it's going to create an instance of a component it can inject the dependencies but in order for that to work
we need to register these dependencies somewhere in our module so let's save the changes now we need to go to our app dot module so here's app dot module okay look at this engine module decorator here we have a property called providers which is set to an empty array in this array we need to register all the dependencies that components in this module are dependent upon for example our courses component is dependent upon courses service so we need to register courses service as a provider in this module so here I'm gonna add courses service now
if you forget this step dependency injection is not gonna work let me show you what happens so I'm gonna comment out this line save back to the browser we get a blank page so that means something is wrong let's open up chrome developer tools with shift command and I on Mac or shift ctrl I on Windows look at this error no provider for courses service this is an error that you might see quite often when building angular apps so the error is telling us that we have not registered courses service as a provider in our
module so back in an app module I'm gonna add this courses service here save back in the browser and we have the list of courses now one more thing before we finish this lecture when you register at dependency as a provider in a module angular will create a single instance of that class for that entire module so imagine in this module we have 100 components and 50 of these components need the courses service in the memory we're gonna have only a single instance of course a service an angular will pass the same instance to all
these components this is what we call the single on pattern so a single instance of a given object exists in the memory so a quick roundup vacuumer component we added courses service as a parameter in the constructor or in other words as a dependency of this class and then register this as a provider in our app module with this implementation when angular is going to create an instance of this component first it will instantiate its dependencies and then it will inject those dependencies into the constructor of this class and this is what we call dependency
injection all right now let me show you a quick way to create a service in angular so we go to the terminal once again you can switch to the terminal window or you can press ctrl and backtick in vs code so here we have a small terminal window we're gonna use angular CLI to generate a service so ng g4 generate previously we use c4 components now we're gonna use s for services imagine we're going to create a service for sending emails this service is going to call an HTTP endpoint somewhere for sending these emails so
let's call this email I know that here I just add the service name I don't need to add dot service ok so this generates two files for us one is the actual service file and the other is a spec file which includes some boilerplate code for writing unit tests for that service so in the app folder look here's our new service email that service the TS so we have a plain typescript class called email service but there is something extra here that you didn't see before we have this injectable which is another decorator function similar
to the component decorator function what do we need this here we would need this decorator only if this service had dependencies in its constructor for example imagine here we had a dependency lock log service of type log service in this case we need to apply this injectable decorate a function on this class and this tells angular that this class is an injectable class which means angular should be able to inject dependencies of this class into its constructor now we didn't use this decorator when defining components because when we use the component decorator that decorator internally
includes this injectable decorator so that's all about injectable and by the way note that this decorator function is defined in angular slash core library right now I want you to use what you have learned in this section and build a page like this so apart from the main heading of our application you have a heading that includes the number of authors so here we have three authors and below that we have the name of these authors rendered using ul and Li so use angular CLI to generate a component and a service and write all the
necessary code render a view like this you can see my solution in the next lecture I love your enthusiasm for learning angular as I told you before this tutorial is part of my complete in ela course where you learn everything about angular from the basic to the advanced topics all in one course you seem to be determined enough to learn angular and I'm so excited to see we've made it this far so I highly recommend you to click on the link in the video description and enroll in my complete angular course so thank you for
watching if you enjoyed this video please like it and share it with others and finally subscribe to my channel for free new videos every week have a great day
Related Videos
TypeScript Tutorial for Beginners
1:04:28
TypeScript Tutorial for Beginners
Programming with Mosh
1,404,391 views
Angular Crash Course | Learn modern Angular in 90 minutes
1:29:09
Angular Crash Course | Learn modern Angula...
Code with Ahsan
39,817 views
Data Analytics for Beginners | Data Analytics Training | Data Analytics Course | Intellipaat
3:50:19
Data Analytics for Beginners | Data Analyt...
Intellipaat
2,275,744 views
Object-oriented Programming in JavaScript: Made Super Simple | Mosh
1:02:49
Object-oriented Programming in JavaScript:...
Programming with Mosh
2,022,154 views
React Tutorial For Beginners [ReactJS] | ReactJS Course | ReactJS For Beginners | Intellipaat
3:49:28
React Tutorial For Beginners [ReactJS] | R...
Intellipaat
727,930 views
🔥4 JavaScript Projects under 4 Hours | JavaScript Tutorial For Beginners | JavaScript | Simplilearn
3:45:56
🔥4 JavaScript Projects under 4 Hours | Ja...
Simplilearn
394,476 views
Angular Tutorial for Beginners | Learn Angular Step by step | Angular Tutorial
2:17:23
Angular Tutorial for Beginners | Learn Ang...
Questpond
393,713 views
React Tutorial for Beginners
1:20:04
React Tutorial for Beginners
Programming with Mosh
3,655,631 views
Angular Crash Course
2:01:32
Angular Crash Course
Traversy Media
1,474,713 views
🔴 Let's build a Whatsapp Clone with NEXT.JS! (1-1 Messaging, Live Status, Styled-Components, React)
3:48:00
🔴 Let's build a Whatsapp Clone with NEXT....
Sonny Sangha
1,555,950 views
Top 50 Angular Interview Questions
2:12:59
Top 50 Angular Interview Questions
Interview Happy
302,128 views
Node.js Tutorial for Beginners: Learn Node in 1 Hour
1:18:16
Node.js Tutorial for Beginners: Learn Node...
Programming with Mosh
5,953,078 views
TypeScript Course for Beginners - Learn TypeScript from Scratch!
3:16:40
TypeScript Course for Beginners - Learn Ty...
Academind
1,806,875 views
PySpark Full Course [2024] |  Learn PySpark | PySpark Tutorial | Edureka
3:58:31
PySpark Full Course [2024] | Learn PySpar...
edureka!
572,176 views
Vue.js Course for Beginners [2021 Tutorial]
3:39:56
Vue.js Course for Beginners [2021 Tutorial]
freeCodeCamp.org
1,308,464 views
TypeScript Full Course - From Beginner to Advanced
3:54:02
TypeScript Full Course - From Beginner to ...
Tech With Tim
90,553 views
TypeScript Tutorial - TypeScript for React - Learn TypeScript
51:33
TypeScript Tutorial - TypeScript for React...
Programming with Mosh
601,675 views
Building the Ultimate Workout Tracker with React Native & MongoDB
3:59:34
Building the Ultimate Workout Tracker with...
notJust․dev
656,053 views
Learn Angular A-Z: Complete Tutorial for Beginners
4:21:33
Learn Angular A-Z: Complete Tutorial for B...
Envato Tuts+
197,705 views
APIs for Beginners - How to use an API (Full Course / Tutorial)
3:07:07
APIs for Beginners - How to use an API (Fu...
freeCodeCamp.org
3,047,146 views
Copyright © 2024. Made with ♥ in London by YTScribe.com