YTread Logo
YTread Logo

Angular Tutorial for Beginners: Learn Angular & TypeScript

Jun 02, 2021
Hello, my name is Muhammad Ali and I will be an instructor for the next few hours. In this course, you will

learn

everything about Angular, from basic to advanced topics, and create and deploy a real eCommerce application using Angular. firebase and the awesome new bootstrap, let me show you a demo of this app real quick. We are going to create an eCommerce app for an imaginary organic store, so here on the home page we have master details. You can select the category and view. all products in that category you can add a product or a shopping cart change the quantity and number of items in a shopping cart it updates in real time and here is our shopping cart again here we can change the quantity of each item and The total price and total quantity of items in the shopping cart are updated immediately if I open another tab and add another product to our shopping cart.
angular tutorial for beginners learn angular typescript
What we have in the shopping cart tab is updated automatically without us having to refresh the page so that all the data that we show to the user is synchronized everywhere in the application and this is the beauty of a real-time application . Now let's see here, we have a submission form and the summary of all the products in our shopping cart and again this summary appears. It updates 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 am an admin user and I have this menu here.
angular tutorial for beginners learn angular typescript

More Interesting Facts About,

angular tutorial for beginners learn angular typescript...

Manage orders here. We can see all the orders in the app, other users will not see this page here, so here we have authentication and authorization as administrator. I can also manage the products, so here we have all the basic 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 you see in many applications in the world real and in this course you will

learn

how to implement these patterns in your applications, so are you excited to learn

angular

and build this application? let's jump in and get started, so in case you are an absolute beginner with

angular

, let me quickly explain to you in two minutes what angular is and why you should learn it.
angular tutorial for beginners learn angular typescript
Angular is a framework for creating client applications in HTML CSS and JavaScript or a language. just like

typescript

which is compiled 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 is very easy and you will You will become familiar with it. In this course, a question that many

beginners

have is why do we need angular? Can't we use JavaScript or jQuery? We certainly can and this is how many web applications are built, but as our applications become more complex.
angular tutorial for beginners learn angular typescript
JavaScript or jQuery code becomes difficult to maintain. We need a way to properly structure our application. Sure there are JavaScript patterns that help us with structuring, but these patterns are difficult to understand for many JavaScript

beginners

and for many applications created. with Vanilla JavaScript or jQuery are difficult to test and that is why in recent years several frameworks have been created and evolved to facilitate the development of web applications. Angular is an example of such frameworks, it gives our applications a clean, loosely coupled structure that is easy. To be understandable and easy to maintain, it also includes a lot of utility code that we can reuse in various applications, especially when it comes to user navigation and browser history.
Additionally, applications built with Angular are more testable, so we can easily write automated tests to test. various parts of our application, as I'll show you later in the course, so to answer this question, no, you don't need a framework like angular to create client applications, but using angular makes your life much easier now that you know what it is angular. Let's take a look at the architecture of Angular applications. Many 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 does.
You see and interact with it, so it essentially includes the user interface or UI of an application. We use typescript and angular HTML CSS 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 data. and while performing any type of processing, our front-end or client application communicates with the back-end to obtain or save the data. One of the questions that many beginners ask me is maash, how do I save my data in angular? Well, it's not like that. In most cases, it does not save the data on the client because it can easily disappear when 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 or API services to make this data available to clients in case you don't know , API means application programming interface. Now, if you leave this fancy name aside, these HTTP services or AP eyes are essentially reachable endpoints. via the HTTP protocol so we can call them using simple HTTP requests to get or save the data if that's too much technical jargon. Let me give you a metaphor: think of a port where ships load or unload, these are points to enter cargoes and outside a city right now imagine these ports are HTTP endpoints, ships are HTTP requests and cargoes are data, Just like we can send a ship to a port to get some cargo and bring us a client application that sends an HTTP request to an endpoint to get some data, that's 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 an API is what makes the data available to clients for a larger application around a complex. domain this is where we implement the business logic of the application like calculating tax and shipping cost based on various parameters, interface or client on the other hand it has to do with presentation so here we have our HTML templates, as well as the presentation. Our application logic This logic has to do with displaying data and responding to user actions, such as what should happen when the user clicks a button or navigates away from a page.
These are examples of presentation logic or logic that has to do with the appearance of the presentation. of an application now in terms of implementation, building the backend requires familiarity with other languages ​​and frameworks and is completely out of the scope of building client applications with angular, so as an angular or 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 purposes of this course we will focus on the front-end and if you want to learn about the backend. development, you can always take a course later, but for now let's focus on one thing and do it well.
In this lecture, I'll show you how to set up your development environment and create your first Angular project. The first thing you need to install is the latest version of Node in case you have never worked with Node before. It is basically a runtime environment for executing JavaScript code outside of the browser. In this course we will not work with Node, but the note provides some tools. that we need to build angular projects so if you have node installed then head to node.js org on this page you can see the latest version of node for your OS 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 is still not completely stable, so go ahead and install the latest stable version.
When you do, open the terminal on Mac or command prompt on Windows and type node - - version so you can see on my machine. I am running node version 6. The minimum version required to build Angular applications is version 6.9. Once you have node, we will use a tool called node package manager or NPM to install third-party libraries. One of these libraries What we are going to install in this lecture is Angular CLI, which stands for command line interface, so it is a command line tool that we use to create a new angular project or generate some boilerplate code, as well as create deployable packages, once again in the terminal. we run NPM install - G which means global and finally the name of the package which is in the angular slash CLI.
If you do not put the dash G here, the Angular CLI will be installed only in the current folder and will not be accessible anywhere. Otherwise, if you are on Mac, you must put sudo at the beginning of this command to run it as administrator. Very good, next we must enter our password. This process will take a little time. Alright, we install Angular CLI. Now, to make sure the installation was successful, we can type ng - - version so you can see. I am writing angular CLI version one dot one dot zero and below you can see the node version on my machine once again it is 6.10 so with angular CLI in place we can now create a new angular project so we write ng new and we call this project hello - world, this generates a bunch of files and folders and then we will use NPM to download the third party libraries.
The project is created successfully now to start coding we need a code editor. The editor I will use in this course is Visual Studio Code or vs Code. It's a beautiful lightweight cross-platform editor and you can download it in the code that Visual Studio reports if you want. i don't like this editor, feel free to use any editor you prefer, you can use sublime, you can use atom or any other editor now, if you are going to use vs code, i want you to add it to the path so you can easily open it from terminal , so here, if you are using Mac, press Shift + P or if you are using Windows, press Shift Ctrl + P, this opens the command palette.
Now here write the code. See this command here. Install the code in the path. with this we can go to the terminal in the folder where we created a new project, hello world, just type the code and dot so that it opens and the code points to the current folder. Now, in the next lecture we will see this structure. We're going to learn what files and folders we have here, but before we get there, let's make sure this app works, so again in the terminal we use the Angular CLI to upload our app to a web server, so we type ng space save, like this which now we have a live development server listening on localhost port 4200 and angular CLI also compiled our app, generated packages for JavaScript and CSS files so we can open Chrome and head to localhost port 42 hundred beautiful, this is our first angular app next.
Let's see the structure of our new Angular project. 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 means end to end and this is where we write end - end to end tests for our application, if it hasn't worked with end-to-end testing, these are basically automated tests that simulate a real user so that we can write code to launch our browser, navigate to the home page of our application, click on some 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 that is beyond the scope of this course, so we don't have to worry about it. However, underneath we have node modules and this is where we store all the third party libraries that our application may depend on. Now this folder is purely for development, so when we build our application, parts of these third-party libraries are placed in a package. and deployed with our application, so we are not going to deploy this node modules folder to a server. You'll see this later in the course below, we have the source folder and this is where we have the actual source code of our application, so we have this application folder here and inside this folder we have a module and a component, so each application has at least one module and one component.
Very soon you will become familiar with these components and modules below, below we have these assets. Folder where we store the static assets of our application, so if you have any image files and you need files and icons, these all go under here, we have this environments folder and this is where we store the settingsconfiguration for different environments, so we have one. file for the production environment and the other one for the development environment now the other files that we have in the source folder are the favorite icon which is the icon displayed in the browser we have the HTML index point which is a very simple HTML file containing our angular application. so keep in mind that here we don't have any references to a script or a style sheet, these references will be inserted dynamically into your page, as I will show you later in the course below, we have this main file which is a typescript file and this is basically the starting point of our application, so in many 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 method. module of our application, which in this case is the application module, so angular loads this module and everything else starts from there. We have this polyfills file that basically imports some scripts that are required to run angular because the angular framework uses JavaScript features that are not available. In the current version of JavaScript supported by most browsers, these polyfills fill the gap between JavaScript features and Angular needs and functions supported by current browsers. Next we have CSS styles 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 test the TS, which is basically used to send you our test environment again, for now we don't have to worry about this outside from the source folder.
We have a configuration file for Angular CLI, it's pretty standard. settings, you don't have to worry about this for the most part, next we have the editor settings, so if you are working in a team environment you will want to make sure that all the developers on the team use the same settings in their editors, so this is where you store your settings. We have this ignore file that basically serves to exclude certain files and folders from your git repository. If you haven't worked with git, don't worry, it's not something you need to know to build applications with Angular it's basically a tool for managing and versioning your source code.
Now next we have karma that configures Jas, which is a configuration file for karma. We are a test runner for javascript code again. We won't worry about running tests at this time. stage now next 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 name and version of your application we have this settings here dependencies which determines the libraries which your application depends on so here you can see we have nine references to angular libraries all these libraries start with angular and then we have the name of the library so the first library here is for animations if you are not going to use animations . in your application, you can remove this here, so that in the future when we use third-party libraries, you will see them listed here under the dependencies below.
We also have another configuration or another key called development dependencies and these are the libraries we need. To develop this application, we do not need them to run our application on a production server. These are exclusively for a development machine, so here we have a reference to the Angular CLI that we are very familiar with. We also have some other references. to karma, which is again a test runner for javascript code, now under this JSON package, we have a protractor that configures Jas, which is basically a tool for running end-to-end tests for angular again, we won't worry about that.
The file here is the TS configuration which has a bunch of settings for your typescript compiler, so your typescript compiler analyzes these settings and based on these settings it will compile your typescript code into JavaScript which browsers can understand again in most of it. You have to change some of this here, just keep in mind that if in the future in a complex project you need to change the typescript compiler settings, this is where you apply the changes and finally we have TS lint as JSON which includes a series of configurations. 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 , now let's make a small change. to this application, so in the application folder, open the application that TS component now, if you have never worked with JavaScript before, don't worry about this code as we go through the course.
I'm going to break this down for you so you know exactly what's happening here, so all I want you to do here is change this string from app to angular app. Now save the file again in the terminal. Look at this message. Webpack is compiled for the Angular CLI using a tool called webpack, which is a build. automation tool gets all our scripts and stylesheets, combines them, puts them in a package and then minifies that package and this is for optimization so here you can see that we have some packages as polyfills that include all the scripts to fill the space between versions. of JavaScript that angular needs and the version of JavaScript supported by most browsers, we have the main package which is all the source code of our application.
We have the styles package which includes all of our style sheets and note that here the style sheets are actually stored in a JavaScript Package, you'll see in a second we also have this vendor package which includes all the third party libraries Now, at the time of recording this video, unfortunately, the Angular CLI does not allow you to customize the name of these packages or add additional ones. packages, but there is a discussion going on and guess what the chances are of this changing in the future now that apart from what I want you to keep in mind here is that every time you change one of your files, that file is a sheet style, a typed file or an HTML.
File webpack automatically recompiles your application and updates its packages, so now here at the bottom you can see the successfully compiled webpack. If you go back to the browser, look without me refreshing this page. Now we have the new title. Welcome to an angular application. So this is a feature of webpack called hot module replacement or hot module reload, so whenever one of the source files is modified, webpack automatically updates your browser. Now let's right click on this page and go to see the page source at the bottom of it. page look at these script tags so all the packages that the web package generator also injected into our index points HTML, so just to refresh your memory here in index points HTML, we don't have any reference to your stylesheet or a script file, so This is something that happens at runtime, so webpack automatically injects these scripts into our HTML index point.
Now let's take a look at these styles that group the js. 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 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 package. A question that often arises is what is the difference between angularjs angular 2 and angular and how do we jump from angular 2 to angular 4. Angularjs was introduced in 2010 as a JavaScript framework for creating client applications and soon gained popularity.
An Angular team started adding new features. the core, but the framework was not designed keeping in mind the needs of today's applications and was also too complex, so the 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 completely different from angular 1 to the extent that it can be considered as a completely different framework, this made many developers unhappy because they had many applications built with angular 1 and each application had a few thousand lines of code that needed to be rewritten. but overall I personally like the direction the angular team took and how they rebuilt angular with typescript.
This is a much better framework, it's much cleaner and it's much easier to understand and work with now after some minor updates to angular 2. something strange happened, we were on angular 2.3 and then suddenly your 4 came out, So many developers, including me, were wondering what happened to Angular 3. We thought we had done something really big here, but unlike Angular 2, Angular 4 was not a new framework with many major changes, in fact, neither. It wasn't even a major update, 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 to call HTTP services, we have angular router to add navigation to applications and some other libraries.
Now all these libraries had the same version, except the router library, to align these versions and avoid confusion. In the future, the angular team decided to go directly to a version 4 of angular, so in a sense angular 4 is not a major update of angular 2 and you can consider it as angular 2.4, it's that simple now, after all this confusion in the community about angular versions, the team decided to remove the version suffix and just call the angular framework, so now we have two types of angular, we have angularjs which is the first generation of angular written in javascript and will die sooner or later and we also have angular referring 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 going to be an angular developer instead of I'm going to be angular 2 developer or I' As an Angular 4 developer I see that it is really strange, we should use versions only when we need to talk about a specific version, for example when we want to upgrade Angular 4 to Angular 5, then everyone knows what is the scope of this update and what the potentials are. breaking changes that can affect an application, so now this is all about angular version history.
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 time, so in this course it has three parts, essential advanced topics and the final project, we will start the essential part with an introduction to the typescript and object-oriented programming, this will prepare you to create angular applications, then we will look at angular fundamentals displaying data and event handling components directives template-driven forms reactive forms consuming HTTP services routing and navigation authentication and authorization deployment and building real-time apps with firebase, so these are the essentials that you will use frequently in real world apps, then we get into the territory of the Advanced Topics and by 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 tests and integration tests, and in the last part we will build that e-commerce. application that I showed you at the beginning of the course, this part also includes some sections and in each section we will create a functionality module in this application, so here we have sections like product management, shopping cart, payment etc., now I understand .
You may be busy and don't have enough time to watch the entire course and that's perfectly fine, so I'm going to give you a shortcut, a shortcut that will allow you to get the most out of the course in the shortest time possible, start with the essentials. Look at all of these sections in sequence, but feel free to skip the section called reactive forms because we will not be using the materials in this section in our final project. Additionally, you can skip consuming HTTP services as well asthe authentication and authorization you need to see. these sections if you want an old backend for your application using frameworks like speed add net express django etc. but this ecommerce application will be developed in this course it does not have a custom backend we use firebase as the backend so things are a little different here if this sounds confusing to you don't worry I will clarify it in the section on firebase so here is my suggestion for you to see these sections in the essential part in sequence and then move on to the final one. part of the project I want you to create this app because that's where you'll see all these moving parts come together, plus those sections include tons and tons of tips and techniques that I've shared with you and these are the things that I've learned in the past. 17 years of working in the industry as a professional software developer really changes the way you think about programming and software engineering.
I have worked very hard for these sections and I want you to see them once you finish the project, then you will have a good understanding. of the big picture, you can then go back and learn about the other sections of 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 watch the animation section or if you want. To learn about reactive shapes, you can return to that section, so focus on the absolutely essentials and then move on to the final project.
Hello, thanks for watching my angular

tutorial

. If you enjoyed this video, please like and share it with others. 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 basic to advanced topics, all in one course so you don't have to jump from one

tutorial

to another, in case you are interested, you can get this course at a huge discount using the link in the video description and if not, it's perfectly fine, continue watching as the section is coming up to create applications with angular.
You should be comfortable with typeface, so in this section I will introduce you to typeface fundamentals and object-oriented programming principles so that by the end of this section you will have a good understanding of type annotations, functions arrow, the interface classes. constructors access modifier 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 to angular; otherwise you really need to watch all the lectures in this section, so now let's get started, so what? This typescript is not a completely new language, it is a superset of JavaScript, which means that 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, for example in typing we have this concept of strong or static writing.
If you have worked with languages ​​like C Sharp and Java, you will know that in these languages, when we define a variable, we need to specify the type of that variable. Now, writing script is optional, so it is not necessary to use this feature, but Using this feature makes our applications more predictable and also makes it easier to debug them when something goes wrong. Typescript also brings quite a few object-oriented features that we have overlooked in JavaScript for a long time. We have the concept of classes, interfaces, access to constructors. modifiers like public and private generic properties etc., you will 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 run time, well of course not all kinds of errors. but there are a lot of errors so there is a build 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 have access to some great tools out there . What I personally love about typescript is the intelligence we get in our code editors. You'll see in this section that typescript is a beautiful language and is basically a superset of JavaScript, so any valid JavaScript code is also valid typescript code.
Now browsers don't understand typescript and are very unlikely to support it in the future, so we need to more accurately compile or transpile our typescript code to JavaScript, so this is part of building our application whenever the typescript compiler kicks in and transforms our typescript code into JavaScript code that browsers can understand. That's enough introduction. Next, I'll show you how to install TypeScript and write your first TypeScript program in this lecture. you will learn how to install time script and write your first typescript program, so here we are in the terminal, we are not going to work with angular in this section, we will focus exclusively on typescript, so first we need to install Typescript globally on our machine, so npm install - g which means global typescript and of course if you are on Mac have it put sudo in front, all good so I installed the latest version of typescript which is currently version 2.3.4 now we can type.
TS C which stands for type scribe compiler - - version again you can see 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 going to create a new file and I'm going to open it with the vs code so code the main TS so now I'm going to write a simple 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 receives a message and here we just log that message to the console like this, then I'll declare a global variable, let's call this message and we'll set it to this string hello world and finally we'll call our message of logging function, so this is just JavaScript code right now, save it back to the terminal, we need to transpile this type of script file to JavaScript so that TSC or the typescript compiler can't yeah, no, if you look at the files in this folder, look we have main. degeus and main dirty s now this transpilation or build step when you are building an angular app happens under the hood so you don't have to manually call the typescript compiler, in fact when you run your app using ng save angular CLI calls the typescript compiler under the hood to transpile all of our typescript code.
Alright, now let's open our main J file, so the main code is exactly the same code that we wrote, but now it's in a JavaScript file, so all the JavaScript code is also valid typescript code now. Back in the terminal, I can run this code using node, so the parent node is and we get the hello world message in the console, so in the next lecture we'll look at typescript-specific features that we currently don't have in JavaScript . Alright, 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 that you have seen in JavaScript, like the var number, we set it to 1 or we can use the let keyword, so let. I count as 2 now, before I explain the difference, I need to clarify that the let keyword is also added to 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 have been around for a long time now we have es6 which is a newer version and it was introduced in the year 2015 and from that time the ECMO script team which is the team that extends Java Script decided to use the number of year 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'll define it. a function, let's call it do something, it doesn't really matter now here I'm going to define a for block, so var we said I to 0 and as long as it's less than 5, let's increment it here, we have a block and then we log in. in the console now finally at the end of this function I'm going to register this eye one more time but with the tag finally and then I'm going to call this function here so in the terminal I'm going to compile this main file that TS and at the same time run it with the main node .
Note that the value of I at the end is 5, so this is the problem we have when declaring a variable using the VAR keyword, which is why we have declared I here inside this block, but it is also significant and is available outside the for block now, if you work 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 In case the closest function is to do something, once we declare I inside this for block, it is available anywhere in this function.
Now let's see what happens when we declare this variable using the let keyword. Now let's look, we immediately got a red underline here indicating a compile error this is one of the beauties of typescript when you are writing typescript code you can catch these errors at compile time before running your application before deploying it now let's mouse over here so this is the error I can't find the name I so now my scope is the nearest block instead of the nearest function and this is the correct way to declare variables which avoids a lot of problems in the future.
Now I want to clarify something, let me see you again. Go back to the terminal first. I'm going to remove the main Jas now. I'm going to recompile our main TS. Well, we have our mistake here. I can't find the name. However, if you look at the files in this folder, we have the main GS, so even though we have a compilation error. the typescript compiler still generated main dejay. Let's take a look at the content of this file, so this is the code that is generated, so by default the 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 the browsers out there now, we don't have the main keyword so our compiled code now uses the VAR keyword and this is perfectly valid JavaScript code so I can go to the terminal and just run this code and get the same result as before, so what I want to clarify here is that the typescript compiler reports these errors but still generates a valid draft, so here is a conclusion for this lecture from now on, anywhere If we want to declare a variable we use the main keyword once again.
We won't stop the build step, but at least we can catch problems earlier during build time. Below we will see the different types that we have and in typescript. In this lecture I will show you the different types that we have in typing, so let's stop. I start by declaring a variable called count and set it to 5. Now if I set this for, say, a character or a string like a note, I immediately get a compile error telling me that this string or character cannot be assigned. type the number now we can do this perfectly 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 compile this perfectly using typescript compiler and we will get a valid JavaScript code, so if I go to the terminal and type the TS main typescript compiler, now look, this is our Jas main, so we have this count variable and we have changed its value, we can run it perfectly, there is no problem, however, code like this is very likely to break at some point in the future because we are likely to use this count variable within a block of four, so our program will break at runtime.
We don't want this to happen, that's one of the reasons. It is better to write the same code in typescript so that we can at least get a warning during the compilation step. Now if you mouse over this count variable, look at the tooltip, you can see a colon and a number after a discount, indicating the type. of the count variable in our program, so here the typescript compiler infers that the type of this variable must be a numberbecause we set it to the number 5. Now, what happens if I declare a variable without initializing it? Let's see its type.
His type now is anyone and that's it. exactly like variables with declare in JavaScript so I can set it to one then I can change the value to true and then set it to its string even typescript doesn't complain about this so what is the solution if we don't know the worth? of a variable in advance is when we use type annotations, so here we add: and after that we set the type of this variable as number and then we look at the third and fourth lines we have compilation errors now in typescript we have some different types, then we have a number that can include any integer or floating point number. we have boolean s, which can be true or false, we have strings, we have any of the ones you saw before, we have an array, so let's say we want to declare an array of numbers, we would use a number in square brackets now, optionally, we can initialize this to an array like this or we can declare any array and with this we can set this to an array with these values ​​one true and false, of course, it is not a good practice, we want to avoid this, but I tell you what is possible with typescript.
Now we also have another type that I love and it's inna, so let's say we're working with a bunch of related constants, like colors, in simple or old. Basic JavaScript we would define constant colors like this, so the color red we can set to zero. We set the green constant color to one and we set the blue constant color to two. Now this is a bit verbose in many object-oriented languages. we have this concept called enum so that we can put all these related constants in a container so that in typescript we can declare an enum like this enum all lowercase, we give it the name as color, now curly braces and here we set the values ​​to be red, green and blue. then we can declare a variable as background color and set it to dot color.
Now look, we have Intellisense here, so this tooltip that 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 set the background color to red dot color 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 which we don't have to set them explicitly, but as a best practice it's better to do that because chances are that in the future someone will 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 reverse this. by explicitly setting the values, if someone adds a new color here, like purple, then it won't change the blue value.
Now let me show you something, let's compile this code and see how we get the enum in JavaScript, so check out the main TS of the script compiler. this code snippet here this is how we can implement the concept of enums in JavaScript we can see that it is very complicated now compare this to how we declare it an enum here it is much cleaner so the more you work with typescript the more you will be able to me love this language, in this lecture I will show you the concept of type assertions in typescript, so I will start by declaring a variable as message and sitting on its string, now here we can write message period.
Look, we get this beautiful thing. Intellisense and in this tooltip we can see all the things that we can do with a string, so all of these elements with these 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 I See and this returns a boolean so we can store the result in another variable as ends in C, however sometimes typescript can be a little confused about the type of a variable, for example I'll remove this initialization here and I will initialize this variable in the second line ABC now look the type of this message variable is any because by default when we don't set a value the type is any now the problem here is that if I remove this and type dot look we don't get that Intellisense no longer because trailing waste is something 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 the typescript compiler that this message variable is actually a string and this is what we call. write affirmations now how do we go about writing affirmations? There are two ways: one way is to prefix this variable with angle brackets and here we put the type as string. Now we need to enclose both parts in parentheses like this, then if you press dot we get our beautiful intellisense with all the functions or methods available on string objects now there is also another way to do type assertions so let's rename this variable alternatively and here instead of angle brackets u.s. message and string are exactly the same the shoes approach is purely your personal preference, but the first approach is what you see most in many tutorials and codebases out there.
I just want to clarify something here, this type of assertion does not change the type of this variable at runtime, in fact it will not restructure that object in memory, it is simply a way of telling the 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 as a function. this function takes a message object and simply logs it to the console like this.
Now in the time script there is a shorter way to define this function, so let's call the other one. Register. Now we don't need the function keyword anymore. We can simply add the parameters in this case. Then we add this arrow and that's why we call it 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, so, if I worked with c-sharp, we've seen this before and c-sharp. We call this lambda expression in typescript, we call it arrow function.
It's exactly the same now. If you have a parameter here, you can even exclude the parentheses, but I personally don't like this because I think it modifies the code a bit. less readable, so I always like to put my parentheses here to tell 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 you don't have the message here. So if you haven't seen this before, get used to it, it's a really nice and clean way to define functions. Now let's see how we can use custom types in typescript, so I'll start by declaring a function as draw point, so this.
The function takes an x ​​and a y and simply draws them on the screen. Now we don't want to worry about the actual drawing algorithm. We just want to focus on the signing of this feature. Now this feature is not so bad. Here we only have two parameters. but sometimes when we work with more complex concepts we can end up with a function that has so many parameters like this, this is really bad and something you should avoid at all times, in those situations it is very likely that a group of these parameters such Maybe all of them belong to a single concept as an example, think about a car, a car has so many different properties that we don't want to pass all those properties to a function like drive a car, but instead you want to encapsulate them inside an object and just pass that . an object here, so in this example, instead of passing x and y here, it is 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 It 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 we are getting a compile time error, but we know that this code will break at runtime because the algorithm in our droppoint function expects x and y properties, so what is the solution? Well, let me reverse this. Well, we have x and y, so there are two solutions to solve this problem. One way is to use what we call inline annotation. Just as we can annotate this parameter with the type as number, we can annotate it with a custom type or a custom object, so here we add braces to indicate that an object will have a property called X, which is a number and also another property called Y, which again is 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 it's a bit verbose and it's also likely that somewhere else we'll 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. Now we have the same concept in typing. If you've never worked with interfaces, let me show you how they work. At the top I define an interface and I will call this dot braces then I add X is a number and Y is a number so with this interface I am defining the shape of an object and then I can simplify this declaration and set the type of this parameter to point to.
This is much cleaner and we can also reuse it in multiple places. Just one thing, note the name. convention that I have used here, so because I am introducing a custom type, I have used the Pascal naming convention, so the first letter of each word in the interface name must be capitalized, so here we have our P for case, not a lowercase P. so when using interfaces always use the Pascal naming convention, so in the last lesson we used 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 they must be part of a unit they must go together this is what we call cohesion now let's go back to this example at the top we have used an interface to define the shape of a point object and below we have an independent function and this is where we have violated the principle of cohesion, so the concept of drawing a point is highly related to the structure of a point.
It shouldn't be a separate function now, if you're going to build a library of utilities for working with points, it probably will be. Let's create another function like getdistance that calculates the distance between two points, so point A of type point and point B of type point and this goes to your code block again. We have violated the principle of cohesion. We have two functions suspended in the air. separated from the point object, since these concepts are highly related, they should be part of a unit in object-oriented languages, we call that unit a class, so a class groups together properties and functions that are highly related now in this implementation , unfortunately we can't 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 to calculate the distance between two points or draw a point inside this interface which we can do is to add a function here. statement, then we will have a drawing function that takes no parameters and returns void, which means it returns nothing.
Now you might be wondering why we don't 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 x and y properties in the same unit, so we don't need this parameter here now in the interfaces, like I said, we can't. If we have implementation, we can only have one function signature, so with this interface we are telling the typescript compiler that our point objects must have two properties x and y and a function called draw, whose implementation is somewhere else, so what should we do now?
Apply the principle of cohesion here, we need to use a class instead of an interface, so at the top I will change the type to class and here I will replace the comma with semicolon so that our dot class has three members, the first two members. They are what we call fields that we use to store data and the third member is a function. Now here in this class we canhave the actual implementation of this drawing function, so we can just define it like this and then add all that logic to draw. a point now similarly we can have another get distance function which returns the distance between this point and another point like this again all that logic will end here now with this restructuring you can see that everything related to a point is in one unit in one class so we have the coordinate that 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 these functions as methods, so when a function is part of a class we call it a method, now with this new implementation you don't want these two functions to be suspended in air, so eliminate this is a much better structure. Also, you won't call draw a point like this anymore, so here's our points class in the next lecture. I'm going to show you how to create such an object and call the draw method, so here's our class. Now we are going to declare a variable of this type, so let's let dot be of type dot and then we can write dot dot.
In this beautiful intellisense we have two methods, draw and get distance, and two fields x and y, now in the time script, we also have a concept called property, which is different from a field, but many people use these terms interchangeably later in this section. Now I will learn the difference between fields and properties. If you want to call the draw method, just call it that so that this draw method is now part of the concept of a point, it's not a function hanging in the air that pollutes the global namespace. Now for this demonstration. I'm going to add a simple console point record here and I'm going to show the coordinate at this point, so X now here I want to add the field X.
We can't use it like this. We need to prefix it with this point so that it refers to this field. in this class and then I'm going to add And is once again this point And now we'll compile and run this program and see what happens, so TSC, what should we write here as main TS and we can shortcut by adding this pipe here, type node? and then main ajs, ok, you got runtime error, cannot read draw property of undefined, so this is the problem when we call this draw method, this point object was not defined because here , unlike the basic types we have in typescript, like numbers, strings, billions, we're dealing with. with a custom type when defining an object of a custom type we need to explicitly allocate memory to it, how do we do it?
Here, where we declare the point object or point variable, we initialize it using the new operator to make this object new. period and here we add parentheses, this is the syntax. Now you can see that we've repeated this point here twice so we can make this code a little bit cleaner by removing this type annotation because the typescript compiler can infer from this assignment here that the type of this object is a point object and let's check that, so look, you're working with a point object now once again, save, so go back to the TS main terminal typescript compiler and then note main, okay, we don't get an error, but you can see that these x and y fields don't have a value because by default they are not defined, so we can come back here and set point x to, say, 1 and point y - 2 now back in the main typescript terminal compiler.
TS point I actually made a mistake before, so instead of this pipe operator we need to use double sign on Mac. I don't know the Windows equivalent, so with this we can combine several comments, so note that okay, beautiful X is 1 and Y is 2, this is how we use the classes that we define in our programs. One highlights 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 about the concept. of a human human could be a class, but when we instantiate this class like John Bob Mary, these are all objects, so that's the difference between a class and an object.
Next we'll look at constructors, so I've simplified the code from the last lesson by simply removing the get distance method because we won't be using it later in this section, so here at the top we define a point class and then underneath we initialize an object knitted. 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 some other properties that we had to initialize this way and maybe a few more? Here's a cleaner way, so let's remove this first.
Well, in object-oriented programming languages ​​we have this concept called a 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. the class I am going to 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 here?
This point X we set to this argument provided parameters do not match any signature of the call target so here we need to provide the values ​​for x and y1 and with this we can simplify this code and get rid of these two extra lines and here is the final result now what happens 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? It is possible, yes, absolutely, but it is a little 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 be optional so here after X I add a question mark and that makes of that parameter should also be optional.
This is a typescript rule and many other programming languages, so now look. I don't have a compilation error when creating a point object without initial values, so here I have created a point object with an initial coordinate. Now, what do you lose in our program? You want to have this rule so 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 the X point to a different value. How can we avoid this? Sometimes we need this feature in our programs because it will make them more predictable. reduces the chance of errors, so how should we prevent the coordinate of this point object from changing after it has been initialized fine?
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, here in our point class we have three members, we have two fields and one method, so let me create a point object and write point, look, these They are the members of the class and since they are all public we can access them here and that is why we can see them in Intellisense. however, I can go here and prefix this field with the keyword private now, once we create this dot object, if I type dot dot, look for X is not in the list, it's not accessible, it's private, so if we try to set point to X 2/3 Look, we have a compilation error in typescript that says that property Now with this technique I can go here and I applied the private keyword in the And field as well and now once I initialize a point object, I can The change is no longer quite innate.
I can only call the draw method. That's 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 not. Not setting an access modifier is supposed to be public, so here the extract method, as you know, is public. I can also add the public keyword here, but this is redundant, it just makes my code noisy, so there's really no need to add this. It's best to keep your code short and clean and use the private access modifier only when you need it.
I'll show you one of my favorite typing features around access modifiers. As you write code with typescript, you see constructors that follow a pattern. I 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 seems a bit redundant. This thing that x is equal to x and this point y is equal to y. Typescript is a fantastic feature. that helps you achieve the same thing with less code, so here we can remove these two fields here and in our constructor we can prepend our parameters with an access modifier, so here I want to have two private fields x and y, I can simply prepend them with the word private key like this, so the typescript compiler will generate these fields for us and it also doesn't need these nasty boilerplate assignments, so if you prepend a constructor parameter with an access modifier with a private or public typescript compiler it will generate a field with the exact same name and would also initialize that field with the value of this argument.
It's one of my favorite features and you'll see that a lot of things in this course now clarify something before we end this lecture, in this case our fills were private, but if they were public, we would use the public keyword here, which means that when we create a pointer object we can access the X field, okay, so I'm going to revert this back to private. Now this implementation has a small problem that we can configure. the initial coordinate of this point and we can also draw it, but there is no way to read the coordinate, so I can't access the point that is the X here, so please show the user what the workaround is.
A simple solution is to define a method like this still Well, here I can always call the point that gets X to get x. value and display it 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 him to be able to change this coordinate later only if he provides a value within a certain range What I mean by that? Let me show you. I'm going to define another method here. Sets X. Now this method will get a value which is the new value for the eggs field.
Let me scroll down. Here we can first do some basic validation. so if the value is less than zero we want to raise an error. Throwing a new error value cannot be less than zero; otherwise we want to set this right x2, this new value. Okay, now with this implementation we can always change the value of the X field like this. Point to that set called property. which is exactly for this use case, so look how I can define a property here, we start with the keyword which is get or set and then the property name which in this case is X and then we will have parentheses. just like a method, okay, now similarly, I'm going to change this to set it with a space so that we have the set keyword and here it's like we have a function and a method.
What is the difference? The difference is that we can use these properties as fields. so here I can read X like this point, note that the icon for Point at which eggs we set it to 10, we don't. I don't have to call a method like this, it's cleaner syntax, so this is what properties are for if you have private fields that you want togrant maybe 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 basic validation, that's when you use a property now, in this case, if I want to grant only read-only access reading to this underlying field, I can simply comment out the setter, so we call this method is a setter and the other method is a getter.
Well now I look at this compilation error, we can't change the value of x. Now let's get this back one last thing before we finish this lesson, so here I have used a capital X for the name of my property of camel case notation. uppercase camel means that the first letter of the first word is lowercase and the first letter of each word after it is uppercase, now what should we do to use case notation for our properties? If I name this lowercase eggs, it clashes with the existing field, so let me reverse this. One convention we use to solve this problem is to prefix the name of the underlying field with an underscore, so let's rename this using f2 and prefix it with an underscore.
Similarly, for the Y parameter or the y field. I'll also use the underscore Y and then we can rename this property from uppercase X to lowercase X once again. we press f2 lowercase its field from the outside but internally is actually is a method in the class, more precisely, it is a method that is a getter or a setter or a combination of a getter and a setter. Well, I have simplified the definition of the point class. I remove the properties so we have a simple solution. constructor and a draw method and we are using this point class below its definition.
Now this is a very simple program with a single file, but the real world application consists of tens or hundreds of files in which we don't want to write all the code. a 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 going to add a new file point to TS now back in Maine , the TS I. I'm going to select all this code, cut it and move it so that it points to TS. Now in typescript we have this concept called modules.
Now what a module is requires a little more explanation, but for now let me give you a simple pragmatic definition in typescript. We can think of each file as a module, so in this program we can say that we have two modules, but this is not entirely accurate because these files are not modules yet, so at the point of TS we have defined this class called period, but it is not accessible anywhere. outside this file so this file defines its own scope so we can use this class somewhere else in our program we need to export this outside so we add the export keyword here and now this is visible outside this file now that By exporting something on top of this file from the font scripts point of view, this file is a module.
Now we need to go back to our main TS and import this class so that we can use it, so that again in the main TS aspect we have a build. The error cannot find the name point because we have not imported it into the main TS, so in the top right import in curly braces we add the name of the types we want to import. In this case, indicate now whether there are multiple types that you want to import. separate them using a comma okay so we import the dot from now here we put the module name in quotes what is the module name is the pass relative to that module from this file so both files are in the same folder that we can use. forward slash which refers to the current folder and then dot is the name of our module, so it is not dot, TS look, we get a compilation error, so our module name is dot, now we no longer have a compile error here and we can instantiate this dot class and use it now, there's a lot more to talk about when it comes to modularity in typescript, but that's all you need to know for now to start building applications with angular because in angular framework we have many types that are exported, so we need to import them into our typescript files and use them.
You will see that in this course the only difference is that the angular modules are defined in a different way, so we do not add the relative ones. path to this module files because these files are not really part of our application, they are somewhere inside the node underlined modules folder, so when it comes to importing types defined in angular we use the library name as module name, for example, one of the libraries is in angular slash core, okay, so here is the lesson in typescript, we divide our program into several files, in each file we export one or more types, these types can be classes , functions, variables or simple objects and whenever we need to use these types, we must import them.
First, when we have an import or export statement on top of a file, that file is a module from the point of view of type scripts in angular, we also have the concept of modules, but angular modules are a little different, no They are about organizing code into different files They are about organizing your application into smaller functional areas, you will 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 course on ela where you learn everything about angular, from basic to advanced topics, all in one course.
You seem determined enough to learn Angular and I'm really excited to see that you've come this far, so I recommend you click the video link. description and sign up for my complete angular course, so thanks for watching, if you liked this video, please like and share it with others and finally subscribe to my channel to get free new videos every week, have a great day in this section . Look at the basics of building apps 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, now that you have some basic familiarity with Angular, let's see. the basic components of angular applications at the heart of every angular application, we have one or more components, in fact in a real world application we have tens or hundreds of components, but what is a component?
A component encapsulates the data, HTML markup, and logic for a view, which is the area of ​​the screen that the user sees. Let's look at the real world example. Let's imagine that we are going to create 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 of this as a view or a component or we can split this view into smaller, more maintainable and potentially reusable components such as the navigation bar component, the sidebar component and the courses component .
Similarly, in the courses component we want to display one or more courses, we can potentially split this component into smaller components and also to take it 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 application or in a different internal application, as you can see, the angular hugs component. -based architecture that allows us to work in smaller, more maintainable pieces that can also be reused in different places, so once again a component encapsulates the data, HTML markup and 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 application component or route component, a real word, angular application is essentially a component tree starting from application component or route component, now in angular we also have another concept called modules, a module is a container for a group of related components every angular application has at least one module which we call application module as your application grows you may want to split that module into smaller and easier to maintain modules, so in our udemy example we can have modules like the course module, which includes all the components for displaying courses, we can potentially have another module like messaging. module that includes a bunch of components for the website area where you can send private messages to your instructors.
We can have an instructor module that includes the components for the instructor dashboards that you don't see and potentially an administration module that is the area. from the udemy website by 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, how much The bigger the supermarket, the more aisles we have in a small grocery store, we probably have one or two aisles at most. The same applies to our Angular applications, so if you are creating a simple application, we only have one module which we call application module, but as our application. grows in functionality, we may need to split that module into smaller modules, where each module is responsible for a specific area of ​​our application, in that module we have a bunch of related components, so this is the big picture as we move forward In this course, you will learn.
About these building blocks in more detail now, let's look at these components in action. Basically, there are three steps you need to follow to use a component. First, you need to create a component. Second, you need to register that component in a module. 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 make sure you run it and it will serve this application, so now if you go to the port of localhost. 4200 this is what you see beautiful now in vs coal.
I'm going to create a new component, so let's open the files panel here in the source folder under the application here. I'm going to add a new file now let's imagine what 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 we use when creating angular applications now if the component name has multiple words we separate them using a hyphen for example if you're building a component called course form, I would call this course - form and then the dot component TS, okay, so the courses component is the TS.
Now here we start by creating a flat type script class for the class courses component to look at the naming convention here again. I am using Pascal naming convention so the first letter of each word must be capitalized and also by convention we use the suffix component in the class name so here is our class so angular sees this class first, we must export. So far we only have a simple typescript class, this is not a component, to turn this into a component we need to add some metadata to it. Angular understands that we use a decorator to achieve this.
In angular, we have a decorator called component. which we can attach to a class to turn the class into a component so first we need to import this decorator on top so import the braces component from now the library name so in angular slash core this is the main angular library that you We'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 a kind of taxes. Now look at the syntax that we used to add the sign component and then we call this as a function, so this is what I call a decorator function now, this function, as you see here, takes one 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, a 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 on the right and if I want to reference an element with the id courses, this is myselector, just basic CSS.
Well, here we want to reference an element called courses, because with components we can extend the HTML vocabulary so that we can define new elements like courses and within that we can have the list of courses or in the future we can define custom elements, an element Custom HTML called rating and wherever we use that angular will render a rating component, so let's remove this. My selector for this component is courses, now the second property I add a template here and that is the HTML markup that we want to render for this component. Now here I want to represent something very simple, so let's add an h2 element and call these courses in a real world application.
Our templates can have multiple lines of code. in that case we can put them in a separate file and I'll show you how it works later in the course. This is a basic component in angular that was the first step. The second step is to register this component in a module currently our application has only one module which we call application module, let me show you where it is, so here in the application folder, look, we have the application but the module now, once again here we have three import statements at the top so there is nothing special here at the bottom we have a typescript class called application module and note that this class is decorated with another decorator function called ng module, so with this we convert a flat Tasker class into a module from the angular point of view.
Now don't worry about all these properties here. such as declarations, import providers and bootstrap, you will learn about them later in the course. What I want you to focus on now is these property declarations and this is where we add all the components that are part of this module, so by default when we build an application, we have a component called application component and you can see that the component is part of this module. Now I'm going to add our new component here, so the courses component, every time I type a class name here and press ENTER, it's automatically imported. at the top of my file, import the courses component from and here is the name of our typescript module, so slash dot that refers to the current folder and here is the name of the courses file of that component.
I know we don't actually have a TS point here. if you add that typescript compiler it doesn't like it so the module name is just the file name without the extension so if you want to add this plugin to vs code just go here and in the extensions search box . look for auto import so currently I'm using point to point auto import to just install it and then you'll have to restart the code yeah so here's our second step now third step back to our component so this is the selector for this component, which means that anywhere we have an element like angular courses, it will render the template for this component inside that element, but where are we going to add that element?
Let me show you here, in the application folder, we have this application dot component. in HTML, this is the external template for our app component, let's take a look, so all this markup you see here is to render the home page and this is what we get now. I want to simplify this. I'm going to get rid of all this added markup. a simple h1 calls this angular and below I'll add our custom element courses so when angular sees this element it will show our courses component template right now again in the browser this is our new home page like this Let's go to the right. click on this courses element and inspect this so look what we have here we have this h1 and underneath we have our courses element and inside this you can see we have the template for our courses component this is how the angular applications as another example. in the root element of this app inside the body element, where is the root of this app?
Well, I can look at the source folder at the HTML index point, so this is the basic template for our application. Right now inside the body element we have an element called application - root, this is a custom element because we don't have an element in HTML called application - root, so from angular point of view we should have a component with a selector for this element and that is our application component, let's take a look at that, so let's go back to the application. folder, let's see an application that component in is, so here is our root component or application component, look at the selector application that is root, so whenever angular sees an element like that, it will render the template for this component inside that element, in this case our template. is external so if we have the template url and you can see the name of our template file after the component in HTML that's why inside the app - root here we have the template for the app component which includes an h1 and the courses element, okay let's quickly review what we have done so far, we created this courses component here, then we register this module in the application, so here in module apt we add our component inside the statements array and then finally we use this component in the template for the app component so let's create a review after the component in HTML added this courses element here three steps ok now there are two problems with this approach the first problem is That this approach is a bit tedious, there are so many steps, so first we had to create this typescript class and then we had to import this decorator component on top and then we had to apply it in this tab script class.
There is so much boilerplate code here now. The second problem is that if you forget the second step, our application will break, let me show you. What's going on? So let's go to the points module of the application. I'm going to delay it. This line here now let's see what happens in the browser. We have a blank page, so now we need to look at the Chrome Developer Tools console tab, so right click anywhere. on the inspect page so we can see we have two errors here we can see the details of these errors in the console tab so here is the error courses are not a known element so if you don't register a component in an angular module I don't know and it doesn't know what to do with this courses element because it is not a native HTML element, so now let me show you a faster and more reliable way to create an angular component.
We need to return to the terminal. but see our terminal is always busy it is serving the application so we have to open a new terminal window or we can open a terminal window inside the vs code so come back here if you press Ctrl and tilde which is the character before the number 1 in In its keyboard aspect, we have a term here and it is much easier to access it and move back and forth between different windows, so here we can use Angular CLI to generate a component, just like we generate 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 create a component called course, so of course look what happened angular CLI created a directory called course and inside this directory added four files, a CSS file to store the style sheets for this component, an HTML file to store the template, a spec file which is used to write unit tests for this component and finally a typescript file which is the actual component now, the interesting thing here is that you also updated the app's dot module and registered this new component.
Let's take a look so we can close this terminal window using the same shortcut which is control and backspace, now we can open the file panel using command + b on mac or control B on Windows ok look at the later module so look inside the statements array now that we have the course component, this way we don't have to remember to come back here and register our new components now before we continue. let me quickly add our courses component that I removed earlier. 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 look at the typescript class, it has all the standard text. code that we wrote earlier and a little bit more, so here we are importing the component decorator and in Innes, which is an interface, we will see this later in the course, this component decorator is applied to our typescript class. a selector has the URL of our template file as well as the URL of our stylesheet file, so the Angular CLI saves us a lot of time. As we move through this course, I'll show you how you can use this tool to generate other buildings. blocks for your applications, so before I told you that a component encapsulates the data, logic and HTML markup for your review, so in this example in our courses component we have the HTML markup but we do not have any data or 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 up as a course list. Now I'll display this title in our template. dynamically, so I'm going to remove this hardcoded tag here in angular, we have this special syntax with 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 the angular framework so here we have this concept of data. binding, so it binds our view to populate this component every time the value of that field changes, the view is automatically notified and updated, now let's save the changes back to the browser, okay, here is our new title, beautiful, now , back here, we don't. We always have to put the name of a field here. We can write any simple JavaScript expression, 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 to get the title and here I am going to return this title, now here we can just call our new get title method like this and we will get exactly the same result.
There you go, course list, so we call this special syntax here string interpolation. In the next lecture, I will show you how to represent a list. of courses here, 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 we set this to an array with three elements 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'll get there now.
I want to display them in our template, how should I? First we do that, we need to change this single code to the backtick character, so remove the backtick. The grave accent is the character before the number 1 on your keyboard. Let me change this too. Now the benefit of using the grave accent is that we can split this template into multiple lines and make it more readable, so I want to put this h2 here and below, I want to add a ul and a bunch of list items 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 , etc., so here we go.
To use a special directive called NG, we use it as an attribute in HTML, so we set it to a string and here we are going to write some expression. Before continuing, we must prefix this attribute with an asterisk. This is a special syntax. in angular, so whenever you use a directive that modifies the structure of a dummy, you should prefix that directive with an asterisk in case you're curious as to why I've covered it later in the section on directives, so for now just remember when we are using a directive thatmodifies the Dom structure by adding or removing an element.
You need to fix that with an asterisk. Now here we want to write an expression similar to the one we wrote for each block, so of course what does this do? That is, with the main keyword we are defining a variable, so the name of our variable is course, this is like a loop variable in JavaScript, everything is a special keyword and courses is the field of this class about the that we are iterating, so when angular sees this expression it is going to iterate over the courses field and on each iteration this course variable will contain the value of one course at a time now within this list.
I know you want to show this course, so once again we use string interpolation with double braces and add this. course variable here let's see the result, save it in the browser and here we have the beautiful list of our courses. Now in most of the real world applications we get these courses from the server and for that we need to use another building block and get I called a service and that is the topic of 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 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 to call an HTTP service here in this component, but there are a couple of problems with this approach, the first problem is that this logic goes to tightly connect 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 depend on an active HTTP endpoint because this will make it more difficult to run those unit tests, so we want to create a fake implementation of an HTTP service, so this is the first problem with writing this logic inside this class inside this component.
You're going to tightly couple this component to that HTTP endpoint. The second problem is that maybe somewhere else in the application. We are going to have another page where we will show the list of courses, maybe it will be part of a dashboard, maybe somewhere for an administrator with this implementation, we have to repeat this logic, the logic to consume that HTTP service in multiple places and that is not good, and finally the The third problem with this implementation is that a component should not include any logic other than the presentation logic, which is the logic behind this view, what should happen when we click when we select an element from a dropdown list etc. details how.
Courses that are retrieved need to be delegated somewhere else in your application, so where should we implement that logic? In angular we use services for that, so we will define a separate class which we will call service and there we will add this logic to get 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 it here in the application folder. I'm going to add a new file. Now look at the course naming convention, dot service, 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 we create a component we use courses does component in TS so notice the difference now here once again you want to export a flat type script class, so export the class course service, so once again, by convention, we add the word service as a suffix to 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 flat type script class, so remove it now. Here we want to add a method to get the list of courses. Get courses. For now we don't want to get distracted by the complexity of consuming an HTTP service, so let's just return the same array that we had in our component and then I'll show you how to consume an HTTP service, so back in our component, I'll select this array here, I'll trim the service and just return it from this method.
Now imagine here in this method we have that logic to consume an HTTP service with this implementation we can reuse this class we can reuse this logic in various places in our application and also this will separate or decouple our component from this logic so back in our component here we are will not have any logic to consume an HTTP service and this allows us to unit test this class without depending on that HTTP endpoint, so while unit testing this class we can provide a fake implementation of the network service now If that's too complicated, don't do it.
Worry, your tests are something for the future. Okay, now we have a service. We need to use this service in our component. How is that the topic for the next conference? Ok, now we have a service to get the list of courses from the server that we need. to use this service in this courses component we first need to add a constructor here constructor because a constructor is where we initialize an object so here we need to instantiate our courses service something like this let the service be a new course service once again. I'm using the auto import plugin, so when I press ENTER, it automatically adds the import statement here at the top, so I'm going to import the course service from the current folder, the course point service right now, again in the constructor, so that we have a service. and then we can initialize this course fills like this, courses we set this up in the service that gets courses, let's test the application and make sure everything works up to this point, save, okay, we get the same beautiful list, 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 the same problem we had before, if we were to implement the logic to consume an HTTP service inside this component, we wouldn't do it.
In order to unit test this class we now put this logic into a different class course service, but because we are directly instantiating this class here we are still tightly coupled to that implementation, the other problem here is that if in the future we decide to add a parameter to the constructor, of course, a service. We need to come back here and anywhere else in our application where we have used this course service and add a new argument as one, so that every time we change the constructor of this service. We end up with multiple changes to our application code, so this is very fragile, so what should we do right when instantiating the course service?
We can ask angular to do it for us so we can remove this line here and add a parameter in this constructor it calls it service type course service with this when ira is going to create an instance or component look at this constructor is this constructor has a dependency this dependency is of type course service so first create an instance of the course service and then pass that to this constructor now with this implementation, if we change the constructor of the course 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 course service object.
The second benefit of this implementation is that when we are going to unit test this courses component instead of providing an actual courses service to this builder, we can create a fake implementation of this service that does not use the HTTP service on the backend . In other words, we've decoupled our courses component from the courses service, so here's the lesson: when you use the new operator like this inside a class, you've tightly coupled your class to that implementation, you can't change this at runtime. execution, but when you add that dependency as a parameter to a constructor, you have decoupled that class from that dependency.
Now you're not done yet. We need to tell Angular to instantiate, of course, a service and pass it to our courses component. This concept is called dependency injection, so we need to tell Angular to inject the dependencies of this component into its constructor as simple as that, that's dependency injection. Many people think that dependency injection is very complicated, but it is actually a $25 term for a nickel and dime concept, so dependency injection means injecting or providing the dependencies of a class. in its constructor now angular has a built in dependency injection framework so when you are going to instantiate a component you can inject the dependencies but 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 the points module of our application, so here is the points module of the application.
Okay, look at this engine module decorator. Here we have a property called providers that is set to an empty array. In this array we need to record all the dependencies on the components. this module depends for example our courses component depends on the course service so we need to register the course service as a provider in this module so here I will add the course service now if you forget this step the injection of dependency will not work. I'll show you what happens, so I'll comment out this line, save it in the browser. A blank page appears, which means something is wrong.
Let's open the Chrome Developer Tools with the command Shift and I on Mac or Shift Ctrl I on Windows. in this error there is no provider for the course service, this is an error that you can see quite often when creating angular applications, so the error tells us that we have not registered the course service as a provider in our module, so back in an application module, I'm I'll add this course service here, save it again in the browser and now we have the course list, one more thing before we end this lecture, when you register in the dependency as a provider in a module, angular will create a single instance of that class for all that module so imagine that in this module we have 100 components and 50 of these components need course service in memory we will have only one instance of course one service and angular will pass the same instance to all these components, this is what calls the single on pattern so that there is a single instance of a given object in memory, so in a quick summary of the vacuum cleaner component we add the courses service as a parameter in the constructor or in other words as a dependency of this class and then we register it as a provider. in our application module with this implementation, when angular is going to instantiate this component, it will first instantiate its dependencies and then it will inject those dependencies into the constructor of this class and this is what we call dependency injection, now let me .
I 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 do a backtick in the vs code. Here we have a small terminal window. We will use Angular. CLI to generate a service so g4 generate above we use c4 components now we will use s for services imagine we are going to create a service to send emails this service will call an HTTP endpoint somewhere to send these emails then Let's call this email. I know here I just add the service name.
I don't need to add the dot service. Okay, this generates two files for us, one is the actual service file and the other is a spec file that includes some boilerplate code for writing unit tests for that service, so in the application folder, look here it is our new email service that services the TS, so we have a simple typescript class called email service, but there's something extra here that you didn't see before we had this injectable, which is another decorator function similar to the function component decorator, what do we need here? We would need this decorator only if this service had dependencies in its constructor for For example, imagine here we have a dependency locking registry service of type registry service.
In this case we need to apply this injectable to decorate a function in 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 in its constructor now we don't use this decorator at all. define components because when we use component decorator, that decorator internally includes this injectable decorator, so it is injectable and sotrue, note that this decorator function is defined in the core angular bar 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 header of our application you have a header which includes the number of authors, so here we have three authors and below have the name of these authors represented using ul and Li, so use the 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 that this tutorial is part of my complete course on ela where you learn everything about angular, from basic to advanced topics, all in one course. You seem determined enough to learn Angular and I'm very excited to see you. I've made it this far, so I recommend you click the link in the video description and sign up for my full Angular course, so thanks for watching. If you enjoyed this video, please like it, share it with others and finally subscribe to my channel. free new videos every week have a great day

If you have any copyright issue, please Contact