Angular - Node - MongoDB & Express (MEAN) Tutorial for Beginners - Getting Started

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hi everyone in this video i want to dive into how you can take an angular app or build an angular app and connect a node express and mongodb app to it now this is an excerpt from my full um course link with a great discount in the video description it's a big excerpt though you'll learn all the theory about how these two ends work together node express and angular on the other hand and we'll also start building this would obviously be awesome to welcome you in this course but this video already should get you started with the mean stack an awesome technology for building full stack apps with angular on the front end welcome to this course it's really great to have you on board as a student in this course we'll dive deeply into the mean stack that stands for mongodb express.js angular and node and it means that we're going to build an angular application which is a client-side framework for building beautiful uis and also at a backend built with node in express and using mongodb as a database and therefore you'll see the full picture of creating a full stack angular application so that's really going to be amazing and in this course we'll cover a lot of cool features all the basics of course but also things like image upload pagination authentication authorization so how to control that only users who created some content can edit or delete that content how to deploy that on one server or on multiple servers and so much more now i'm really excited to dive into all of that together with you the question now is who am i my name is max i'm maximilian schwarzmuller i'm a freelance web developer and udemy instructor i got multiple five star rated courses here on udemy like my angular the complete guide course which is a great starting point before you dive into that course and i worked with angular and all these technologies shown in this course for a very long time i'm so happy to share that knowledge with you and i actually created this course two years ago already i completely revamped it now in 2018 so that you're learning the latest and greatest of all these technologies and with that let's get started and let's dive into that let's start by understanding what the mean stack actually means and comprises and let's then add all these cool features i was mentioning step by step so what does mean stand for what are the different components we'll learn about in this course mean comprises a set of four technologies and this is what it stands for the m stands for mongodb and it's the database we'll use in this course so the part where we will be able to persist the data the users of our application generate like the user data itself but also like posts or messages they send things like that the e stands for express and express js is hard to understand without the n so let's quickly fast forward we also get the a and the a stands for angular now i'll come back to that n which is related to the e but angular is our client-side technology it is a javascript framework in the end which we will use to render a nice dynamic ui user interface to our users it runs entirely in the browser not on the server at all and therefore it really has just one job presenting a nice and pleasant interactive and reactive user interface now what's the end then well you probably already saw that something is missing we got a database and we get something running in the browser but we certainly also need to run some logic on the server for example authenticating users this is not something we can do in the browser because a browser code can easily be hacked or changed and b it's way too complex it would take up quite a significant amount of resources and slow down our front end our user interface n stands for nodejs and it's the javascript runtime the server side language we'll use in this course for our server-side code so for our core business logic that runs on the server and now the e also is related to it because whilst node.js is the language we'll use on the server express is a framework for node.js that makes working with it easier you wouldn't need express shares per se but it makes working with it much easier just as angular is a framework for javascript in the browser you don't need it but it makes things easier but let's take a more detailed look at all these things now i want to look at angular first as i already said angular runs on the client side in the browser it's a framework building up on javascript or using javascript and it's used to create so-called single page applications this essentially means that it handles the entire front-end logic so everything your user is going to see angular is responsible for it but i'll come back to it in a few seconds angular's job is to render the user interface with dynamic data and that dynamic data part is important of course its job is not just to render some static html and some css we wouldn't need javascript for that its job is to update the ui whenever we have new information let's say when you create a new post we want to immediately update the ui to show that new post there it also is responsible for handling user input so validating that user input and also sending it to the server because that's the third part it does it communicates with our backend so with that node express combination that seems to be responsible for that angular provides a mobile app-like user experience because since we handle everything in the browser through javascript we never need to reload the page we just change parts of the page with javascript through angular and therefore everything happens instantly in a very reactive way and that is the feeling we know from mobile apps now that is still only the front end though as i said node.js is the language we're going to use for the backend so on the server side which we also build in this course node.js is a server-side library javascript runtime and you know that javascript can run in the browser while node.js simply takes it add some things that are useful on the server like working with files working with http requests and now we can use javascript on the server too pretty amazing node.js listens to incoming requests and is able to send back responses for example our angular app could send a request to fetch a list of all the posts and node could handle a request do something reach out to the database and send back a response with all these posts node.js executes server side logic in general so authentication anything we don't want to run on the browser for security or performance reasons and node.js is able to interact with databases and files angular can't do this it doesn't have access to any file system and especially not to a file system on some remote machine on a server and whilst theoretically you could connect to a database from angular since all your client-side javascript code is visible to users you can have a look at it in your developer tools of your browser it would be very insecure to connect your database there because you would expose all your credentials and everything you don't want to do that therefore node.js is an alternative to php if you know that or ruby on rails asp.net things like that and it's rarely used standalone just like these languages you typically use a framework along with it and that framework you typically use is express express is a node.js framework so it still uses node.js the same language but it adds a lot of utility features so it offers additional functionalities or in general it makes things easier express.js is middleware based and we'll see what this means once we dive into the code it basically funnels incoming requests through a chain of middlewares of steps where we can do something with the request read some data from it manipulate it check if the user is authenticated or basically send back a response immediately this chain allows us to write very structured code and you will learn everything about it in this course of course and last but not least it includes routing which means we could render views so html page pages with it we're not going to do this in this course though because angular should handle our entire frontend and again this is also something we'll see but more importantly we can handle different requests to different endpoints which will be important for connecting angular to the back end because if we want to fetch a list of posts we want to send some requests to slash posts so our domain slash posts if we want to create a new post we want to send a different request to our domain slash post for example and express.js allows us to implement this routing logic so that different requests to different urls are handled correctly again this will all be implemented step by step throughout the course so to sum it up express.js simplifies the usage of nodejs it is a tool we definitely want to use if you have a php background for example you could compare it to laravel for php it makes things easier there's one thing missing and that is mongodb of course mongodb as i already said is a database it's a nosql database to be precise and it stores so-called documents in so-called collections now chances are you might have heard about sql databases like mysql microsoft sql where you have records rows which you store in tables now nosql has a different logic than sql databases but in general it's still a database so you store your application data on a server so that it persists across page reloads across the user leaving your page things like that so any data that is not just temporary data definitely has to be stored in such a database now that nosql thing means that this kind of database enforces no schema so you can have different documents with different pieces of information in the same table or collection as it is called here and it also doesn't really work with relations you will see in this course that we can kind of relate different documents with each other but in general it's way less strict and flexible regarding relations than a sql database is a nosql database is more about storing multiple unstructured documents though you can get some structure into it and we will actually do that in this course i'll come back to what exactly mongodb is and how it works in the respective sections no worries now last but not least it's easily connected to node that's pretty cool it's very easy to integrate or node express to be precise and we don't connect it to angular i already said this theoretically you could find a way but you don't want to do that because you don't want to expose your database credentials in your browser site code which can easily be viewed by the user it's accessible in the developer tools of the browser so mongodb is a powerful database which can easily be integrated into a node express environment and it's very popular these days because it's very flexible and it's highly scalable it's able to handle a large amount of throughput so requests per second or right actions per second and read actions per second and we'll dive deeper into this in the sections where we start working with it now you could theoretically replace it with a different database you could use a sql database in a node express angular application too you're not limited to mongodb and it just wanna really emphasize this i'm using mongodb because it's part of this popular mean stack and it has some advantages but depending on the application and the type of data you're storing if it's a data with a lot of relations maybe a sql database might be better and whilst we will use mongodb in this course i just want to highlight this is not a must you could use any database here the core logic will dive in release the connection of angular and node so with that let me quickly come back to what exactly that single page application thing meant and how the big picture of such a mean app looks like before we start diving into our setup of the course and start building our min app now as i said in this course we'll build a single page application with angular now what is that what is a single page application well in an angular app we'll have one root html file a so-called index html file and we will serve that from our node server or from a different server that's important it can be totally decoupled of our node backend and it actually will be and this html page basically includes some script imports that houses our angular app so the angular framework and our own code and we use that application to dynamically re-render what the user sees without ever requesting a second page to be rendered by the server why because by having this pattern we never need to reload the page just because the user maybe clicked on a post and want to see the details we can instead navigate to that page directly because we don't really leave the page we just remove some elements from the dom and add new elements and all of that is handled for us by the angular framework it's really convenient to use and to work with the dom with it and therefore we have a powerful way of immediately changing the page maybe showing a spinner whilst we're fetching some data behind the scenes so that list of posts which we probably still need to get but we will do that behind the scenes and this provides a highly interactive mobile app-like feeling a very responsive and fast web page where we never have to wait where things always happen and that of course is a great user experience and this is why we will use javascript and angular therefore for the entire front end for the entire user interface and we will use node express and mongodb as a backend to which we reach out behind the scenes to fetch data and send data but the whole user interface is handled as one page only which is dynamically re-rendered all the time by angular with that let's have a look at the big picture how does the entire mean stack look like in this course or in general not just in this course we have the client side and the server side that's important client side is what the user sees the web page as it runs in the browser server side is somewhere on a server we deploy where we run our business logic and which the user only indirectly accesses we'll see how that access works in a second so on the client we use angular which is a javascript framework so we also use javascript implicitly and we use a tube build that user interface on the server side we use node express and mongodb node express for the logic and mongodb as a database as i said you don't want to connect directly to it from angular now the client side angular is responsible for the user interface so for the presentation it's a single page application as i explained in the last lectures and that single page application can be rendered by our node backend so we could have one route which essentially returns that single html page but it can also be totally decoupled from that and be served from a totally different host some static host like aws s3 for example now on the node application we have our core business logic especially the logic that should not be exposed to the client due to security reasons or performance reasons we have our persistent data storage so that database and we also put our authentication logic there for example it's of course part of our business logic i just want to really emphasize that here the logic where we decide whether an email and a password is valid happens on the server because it can easily be fiddled with on the client not so much on the server how do we connect the two pieces then well we exchange requests and responses and these requests and responses are sent behind the scenes so-called ajax requests you might have heard of this before and we use exactly the same pattern in angular these are requests which can be sent without us needing to reload the page which is of course exactly what we want therefore the type of data we exchange is not html because we never want html code we do all that presentation and re-rendering logic with angular instead what we get is so-called json data that's a data format that's really efficient for encoding data like a list of posts and you will see how it looks like in this course this is the big picture this is how the mean stack works and this is exactly what we will implement in this course so with that i'd say enough of the words let's get started and let's start setting up the base development environment we'll work within this course and let's start building our mean stack application so for this course we will need a couple of tools and we'll install and add them step by step for example mongodb will be added a bit later what we'll definitely need is node.js for one because we will write and run node.js code our server-side logic but also because even angular needs it even if we were not to create our own node app not because angular uses node.js language features but because angular actually is a framework that has a more complex build workflow so the part where we take our source code as we write it as a developer and transform it into code that runs fine in the browser that's a bit more complex with angular because angular for one uses typescript a superset to javascript so a different language that's heavily based on javascript and that's important that does not run in the browser and to make it run we need to compile it and it will be done for us no worries but that taskrunner doing the compilation in the end is nodejs for example so this will run all throughout the development process we won't need to write any code for that but this is some stuff that happens behind the scenes and not just the typescript to javascript compilation the angular code itself needs to be bundled and optimized and we need to reduce the code size by stripping out unused code and minifying it and all these are tasks handled by node.js on our machine whilst we are developing the application or when we are finishing it up basically and nodejs will be used for that too so we need it for these two reasons for the node.js code we write for our backend and for the angular build workflow and to learn more about angular and the angular workflow and how it works definitely check out a course dedicated to angular because whilst they will cover some angular basics in this course in general i do expect you to know the very basics about angular this is not a course for you if you never touched angular before so with that out of the way download node.js from nodejs.org and there pick the latest version 10.1 in my case if you're facing issues with that fall back to the older version but in general it's recommended to use 10.1 or whatever the latest version is when you're viewing this simply click on that and it will download an installer through which you can walk it's available for both mac os and windows and also linux and it should automatically give you the right download there and once you successfully installed it through the installer we can think about setting up an angular application because that is actually what we'll start with in this course for that we'll use another tool and that's the angular cli cli stands for command line interface and it's the defacto way of creating angular apps because of that more complex build workflow i mentioned we need a lot of tools that compile our code optimize it and setting all of that up on our own is pretty cumbersome and error prone dcli gives us a project setup where all of that is taken care of and where we can focus on writing our angular code our logic dcli is installed like this and it uses npm the node package manager to install the cli tool globally on our machine with this first command here npm the node package manager is installed together with node.js automatically so if you installed node.js you will have npm now let's therefore now install the cli i already got nodejs installed so i can just fast forward to this step and to install the cli you should open your terminal or command prompt on your machine and then run npm this node package manager command which is available with node.js install g for globally because we want to install that angular cli globally on our machine so that we can use it from anywhere on our machine and then the name of that cli package is at angular slash cli and make sure to not mistype this the naming is important you can add a add latest to absolutely fetch the latest version but it should by default give you that version now on windows this command should be fine like this on mac and linux you might need to add a pseudo in front of this to get the right permissions to execute this command hit enter thereafter and enter your password if you are prompted for it and thereafter it will download that cli package from npm's repository and install it on your machine this can take a couple of seconds up two minutes and i'll be back once it's done so it's done installing and in my case i got some errors in between but that's no problem as long as it finishes with some output where it mentions the package name and version and says updated or added eight or the number can actually differ packages so if you see something like that it succeeded you may ignore any errors that happened in between it was able to recover from these now once this is installed we can create a new angular project with dcli and we'll add node and and express to that project setup throughout the course but let's start with the front end because that is how we can quickly see something on the screen so let's create a new project and for that navigate into the folder where you want to create the project once you're in that folder and you can get there with the cd command on your machine create a new project with ng new that is a command now available due to that cli package ng is basically a command made available by that and then the name of the project and i will name it mean course but of course you can pick any name you want just make sure it's not starting with a number and it's not named test that is forbidden but anything else is fine mean course should work and once you hit enter it will set up that project it will create a lot of files in there most of them are configuration files for that workflow we don't need to worry about them and it will also give us a little dummy app with which we can start it will also install all the dependencies like the angular framework and other dependencies that framework depends on but also a couple of build or workflow dependencies so dependencies that compile the typescript code dependencies that optimize the code things like that so this can take a while and i'll be back once it's done now once it is done you can navigate into that newly created folder with cd and then the name of that folder and in there simply run ng-serve to bring up a development only server and this is not a server you will use to deploy it i will show you how to deploy that app towards the end of the course this is a development only server that allows you to preview your application double clicking on the index.html file won't work because that will use the file protocol and not the http protocol and therefore many features we need are not enabled and this gives us a real web server running on our machine at this address you see here http localhost 4200 by default and you can then go to a browser and simply visit localhost 4200 and on that url you should see something like this some dummy starting page dcli gives you by default now with that setup we of course want to work on our code and for that we need some ide or some advanced text editor that makes that easier now you can use any id you want like sublime atom webstorm in this course i will use visual studio code now let's set it up and open our project in the next lecture so in the last lecture we created our angular application and now we want to edit it as i mentioned for this we want to use an ide or some advanced text editor because that simply makes working with our code much easier in this course i will use visual studio code and that code part is important not visual studio visual studio code it's a free ide totally free it's pretty powerful it's highly extensible it's awesome and it's available for mac but also for windows linux you can pick your installer version here if it doesn't auto select the right one automatically simply download it then and walk through the installer it gives you there should be nothing special about that and once you got it installed open it if you open it it should look something like this you probably see that welcome page and there you can click open folder to open that angular project we created with the cli a few seconds ago if you don't see that page you can always open it through file open now let's click open folder and navigate to the folder here i selected that mean course project and i can click open now and this loads it into this id so that we can work on it there now the idea might look a bit different for you maybe it doesn't have this dark theme it probably has different icons and that is simply something i fine-tuned for myself so i like this way of it looking and working and i will show you how to get there if you're using a different id you of course have to fine tune it on your own for visual studio code i want to install a certain extension first of all two extensions to be precise and for that go to view extensions you might also see a bar on the left where you can click on extensions icon and on this page make sure to install angular essentials now here i already got that installed you can search for angular here and you should quickly find the angular essentials package search for angular essentials otherwise and that's a pretty amazing collection of different extensions that enhance the ide to work better with angular so simply install this with the install button and feel free to skip or read through the documentation here to find out what's included and how it works besides that i use one other extension which is purely optical it's the material icon theme here so by searching for material you should find it also install this if you like the way my icons look in this course it's purely visual it gives you nicer file icons and i quite like these so with that you can go back to view explorer once you're done and you should see something like this well i also use a dark theme and you can get that same look by going to the code thing here preferences and there color theme and here i'm using dark plus by default you probably are using light plus or light now you can try out these different themes here by simply clicking on them you can always switch and choose the style you like now with that you get the same setup as i do now let's get started working on our angular app this is the folder the angular cli created for us time to edit it so let's quickly start working on the angular app we created this is the folder dcli gave us and as you can see it has a bunch of subfolders and files as i said most of these files are purely for configuration and we don't need to worry about them the package.json file is interesting because here you can see all the dependencies and development only dependencies of the project and later once we start adding some mongodb related dependencies we'll also see them here we got files for configuring the typescript compilation and you don't need to worry about that the defaults are fine we get the angular json file which is for the angular cli and we also don't need to worry about this file in the course for now then e2e is for end to end testing we won't cover this here node modules actually stores all these dependencies which are listed here so they are installed into that folder so that they are available to the project and you can always recreate that folder by running npm install inside this project folder in the terminal this will read the package.json file and download and install them all into a newly created node modules folder and the source folder is where our angular application lives in here we got even more config files which we can safely ignore and then we got this app folder here now there we write the meat of our angular application angular actually uses components i'll come back to that in the next section and we create our whole application by composing our ui from such components therefore if you have a look at that app component html file you can see what we see on the screen here this is actually the content we see here with some dynamic content here and as i said i won't dive deeply into all the basics of angular but a brief refresher will be given in the next course section and if we change this page here and for example say our first app and we save that and ng server is still running that's important it will automatically recompile and reload this page without us doing anything but again make sure that the ng-surf process here is still up and running you can quit it with ctrl c but you should only do so once you're done with developing for the day when you are developing it has to run so that it watches your changes recompiles the code and reloads that page and this is the front and we'll work with we'll add more components we'll compose a complex ui with it and we'll start working with angular here now again i'll walk you through that project and how angular works in a brief summary in the next section for now let's leave it at this little change here so that we can see that we were able to do something just one more word i said that we create a single page application and you can actually see that single page here this index.html file in the source folder this is the file served by ngserv right now or by your favorite host towards the end of the course we will deploy the app together this actually doesn't contain a lot of content for one because the script imports are injected by our build workflow i said that we have quite an elaborate build workflow and it will actually take our optimized angular app create the output files and inject them in there we don't see this during development because it happens in memory but this is what will happen we see it has one html element in the body and that actually is not a default html element that is our custom component you can see it here on the selector this is how angular works and how we take control over the ui with angular and how we can then start composing our ui with angular components and now with that i'd say let's continue and let's find out what's in this course for you before we start diving deeper into angular and building that whole mean stack from ground so now that we know what the mean stack is and that we have our basic project set up for this course let's see what else is inside of this course so we're pretty much done getting started in the next course module we'll dive into building the angular front end you'll get an angular refresher there too though i also recommend diving into some dedicated angular resources just as for node and express and mongodb if you want to learn more but with that we'll build the core foundation the things we can see or will at least start building these in that module thereafter we'll already attach our back end the node express backend so that we can actually do more than just display a beautiful ui well and we also want to work with data and want to store and fetch that data and for that we obviously need a database so in the module thereafter we'll add mongodb to the party and therefore a really great database i'll show you how to add it and how to work with it from node express and therefore also from angular once we did that we'll enhance our app now that's a very broad term but we'll add some things to the angular app to the node backend to turn this into a more realistic and better app so this will be a really important module thereafter we'll already dive into image upload that's a super interesting topic which i was often asked about in my other courses here we got it here you will learn how to let the user select the image in your angular app and then upload it to your node express server and store it there and how to then also of course retrieve it we'll thereafter have a look at another very popular topic pagination we get a lot of data in our database and we typically don't want to fetch all that data in one block that is typically not what you want to do because it impacts performance is more data to download so here i will show you how you can add pagination so how you can select chunks slices of your data to display on a given page and thereafter we'll dive into authentication how can we add users sign up log in and how do we store the information whether a certain user is logged in in our client-side app and use it to reach protected resources on the server thereafter we'll dive into something which is kind of related to authentication authorization authorization is about ensuring that only users who created a post let's say can edit and delete that post so we'll add this in this module we're nearing the end of the course thereafter and we'll dive into error handling what does this mean and how could we elegantly handle errors in our angular app once we're done with that we're pretty much done and we'll put some optimizations into place both on the back end and the front end regarding our code our code structure but all regarding performance and finally we'll of course deploy our application actually in two different ways on one server and on multiple servers and i will explain the differences in this module of course and with that we're done and we'll have a complete mean app finished and deployed and i'm very confident that once you finish this course you'll have all the knowledge you need for your next mean project so now that you know the structure of this course the remaining question is how do you get the most out of this course because that is honestly very important to me obviously i strongly recommend watching the videos and watch them in the order i uploaded them because with that order i did my best to ensure that you have a great learning experience and a good learning curve you might need to increase or reduce the playback speed for some videos or pause sometimes because i try to go through the content of this course on average speed i'm not super slow and i try to not be super fast but everyone is different when it comes to this some students want a slower pace some students want a faster pace and really use the tools the udemy video player gives you to adjust this to your needs now watching the videos is great but i always recommend that you code along write the code that i teach you in this course on your own follow along you will find code snapshots provided by me attached to the last lecture of every module so that you can compare your code to mine in case you're facing any errors because that really enhances the way you learn if you code along and as i said use the course resources like these attached code snippets but also the extra links i have in the last lecture of every module to dive deeper to solve errors and to really become a node angular master now finally and that's also important there is a q a section in this course and if you got any course related questions so questions related to the course source code or some logical question about some concept i taught here please post them there i do read and reply there regularly now asking is great but often you can solve issues on your own by googling by comparing code and you can also help other students if you see open questions please all the reply there it can be hard to do that because you're afraid that your answer might be wrong but who cares even if it's wrong then you'll learn again because someone is going to correct you i really want you to interact because by answering you will learn the most asking is easy answering is much harder and it challenges you to think about a problem to come up with a solution and if you want to become a true master definitely dive into questions and answer them that will really help you the most i promise and that is how you should get the most out of the course and really well become a great angular node developer by the end of it welcome to this module now that we're all set up and learned how we set up our ide and create our first angular experience let's dive into our course project now you will learn how the mean stack works on a real project we'll build a simple posting messaging like app where users can create and edit and delete posts and see the posts of other users which they can't edit though so a mini social network we could say this is what we built and we'll actually start with the angular front end so if we have a look at our big picture here on how the mean stack works we're going to focus on the left side here on the client side and the reason for this simply is that by doing that we can see something very quickly the back end holds a lot of logic but we don't see that much of that if we don't have a front end where we can actually render our data and display it so we'll start with the left part because we can always work with some dummy data until we have the real backend added but we get a beautiful ui right from the start so this is what we'll start with in this module and it will also give you a brief reintroduction to angular now i strongly recommend going through a dedicated angular course first this is not a course that teaches you angular from the ground up but i will cover the important basics and briefly refresh them so that we're all on the same page now with that let's jump right into it let's create a new angular project and let's start building our course project with it i'm back in that first angular app we created in the first course module there we haven't changed that much just added this line in the app component and now i will build up on that project and use it for our mean project now first of all let's understand this folder structure a bit better and let's understand how an angular application actually starts for that i need to start it so i'll bring up my terminal integrated into my ide here and run ngserv to start that build process which we should keep on running and which also starts this development server where we can preview our angular application here it is not that spectacular to be honest but we'll add a lot more to it very soon now to understand how it starts let's have a look at its source code actually and if we inspect that source code what we can see is that we don't see a lot do we we got a basic html5 skeleton and then we got a bunch of script imports at the bottom that clearly is important but that's roughly it there is no content on this page and yes our page doesn't have that much content on it it's only our first app but at least this text should be visible right but we don't see that text here instead we just have app root here and this is an important thing this is not a default html tag or element this clearly has to be related to our angular application as do all these script imports down there and that's exactly what's happening if we go back to our application we can clearly see that what we see on the page is the content of the app component html file and that really is important because angular thinks in components and what we do here is we build our own components or you could say our own html elements what we loaded the page we loaded actually was this index.html file and there we see that app root right we covered that before now the script imports are missing here because they're injected but it's this app root element that is loaded and as you already learned this is our own component here is the selector our own html tag we assign so to say so this is how this is roughly connected and the cli in this build process which we have up and running takes our code bundles it up adds all the angular logic from the angular framework to it and therefore creates a bunch of script files which we don't see here because it's loaded in memory for development and injects these script file imports into the index.html file and what's happening there in the end is that this actually then detects this approved element and swaps it with the content of our component and content is not just the visual part the html part it would also be any logic we have here and we will add a lot of logic throughout this course of course so this is how we connect these two things but where is this swapping logic defined where do we tell the browser that this is our own tag so to say well we get two other important files for that the app module is one important file this essentially is a file which is important for angular it defines the features our angular application has because angular thinks in applications and applications are split up in modules or in this case in one module and that module defines the building blocks of our application and components are not the only but probably the most important building block of an angular application and what we're doing here in the zap module is we're declaring the app component this is registering it with angular so now angular is aware of the app component but this alone would only allow us to use that component selector in other angular components not in the index.html file this is allowed by adding it to the bootstrap array two and we typically only have one component in there because we only have one root component in a typical angular application and all other components would be somehow nested in that root component and this is also how we will build our application in this course so we get that bootstrap array which essentially tells angular that it should search the index.html file which is loaded or in general the page in which the angular app is loaded for the app component identified by its selector now the only remaining thing is what actually starts the angular application and that is the content of the main.ts file this is executed first and that is simply how it's defined you don't define that this is what angular does or how the cli packages up our files in the end the code in here will execute first and what we're doing here mainly is executing this line we import a bunch of stuff because for a typescript to use a certain feature in the file we need to import it so the typescript knows where the code for that feature is located and then we have this line here which uses angular feature platform browser dynamic that's a function we execute that it essentially starts the angular application in the browser and angular is a browser side framework so that seems to be important and then we call another function on an object this first function seems to return and that's the bootstrap module function and there we pass a link to our own module the app module which is located in the app module file we pass this as an argument and this essentially tells angular start your angular application and start it with this module in mind so now angular parses these modules though to say registers these components which are declared imports some other modules because there are some modules angular ships with like the browser module which contains some core features of the angular framework and last but not least it detects the bootstrap array and it then looks on the page it's running on for the selector of this component and this is how the angular application starts how it detects the building blocks that make up that application and how we in the end see our first step on the screen because we use our own component which is understood and used by the angular framework i already mentioned that angular thinks in components that components are one of these crucial things you have to understand when working with angular essentially you compose an entire page of these components you build it with these components because the advantage of this is that you have small easily to maintain and manage building blocks for your ui which you can even reuse because some components appear more than once on a page now here is a screenshot from the official angular dot io page and we can easily deconstruct this into different components to understand this way of thinking in components we could think of having a header a brand and some feature component so three sections of the page which are kind of independent from each other and which we can define in their own components so that we can easily manage the code for that given part of the page but we can and we should be even more granular than that we can clearly identify some navigation items in the header and our search and even in the navigation items we could argue that each navigation item on its own is its own component now you can of course go as granular as you want it probably doesn't make sense to wrap a single html element into its own component at least in most cases but if you got a certain part of your ui that really is decoupled from other elements on the ui and that probably also contains some logic like the search here it definitely has some logic like type ahead or filtering or showing some preview so if you got that then you want to put it into its own component so that you can easily manage the code and possibly reuse it that search could be used in other parts of the application too and we can also do that here for the bottom of this screenshot in the feature component now this could be all in one component but maybe we even split that up a bit more because we might want to reuse that image maybe it contains some logic for lazy loading the image and we want to use that on other parts of the page too so as you can see you can go very granular and you probably already knew that if you worked with angular before and we will go granular in this course too we will build our mean stack application the front end of it we will build that with a lot of angular components so let's get started writing some code and let's dive into that component world in this course we'll build an application where users can create posts can read the posts of our users edit their own ones and so on so let's start working on that and we certainly don't want to handle all the logic in one component only because that would quickly explode in size theoretically it would be possible though that's important to understand but i want to create more than one component and we can simply create a new component by going to that app folder this is where you manage your angular app and the parts that make up that app and by adding a new subfolder there you typically put new components or blocks of components into subfolders to keep your code organized now in there i'll create a new component for creating a new post because that sounds like a good start if you want to work with posts we need to be able to create them otherwise reading them will be hard so i will create a new posts subfolder here which should hold all my post related components and since each component typically is made up of more than one file we got a template for the html code and a css file for the styling as well as the typescript file for the logic i'll create yet another subfolder in there to organize the files of a single component in there now this is up to you you could also use a flatter folder structure where you don't use that many subfolders audio the subfolder way here so in here i want to be able to create a new post and i'll name this post dash create because i'll create the post create component in there the file which i create in there is the post create.component.ts file and now the file name theoretically is up to you but it's a convention angular to include dot component in component files or in general include a description of what's in the file in the file name with this dot notation as we do here dot ts is the extension because we use typescript and the part in front of that there you typically use the kebab case so dash separated words for describing which kind of component this is now i got that post create component in there but a component as i said typically is more than just the logic it at least needs a template now theoretically you can also define that html template in this typescript file but since we have a bit of a more complex template and in general it's a good practice to create a separate file so that will be the post create dot component dot html file now so that's the html file belonging to that component and with these two files we can work with that now in the typescript file we create a component by simply creating a new class a class is a typescript feature it's all available in the latest javascript versions it essentially allows us to create a blueprint for an object though we will never create that component object on our own we just give it to angular and angular will instantiate it and create it and use it we just define how such a component would look like and that includes a name for it there the convention is to use basically your file name but now in that notation here post create component so the individual words starting with capital characters and component at the end and we actually as i said create a class here so don't forget the class keyword and now we get a new class which essentially is just a typescript class we turn it into a component angular understands by adding a so-called decorator to it a decorator is a typescript feature you add an add and then the name of the decorator and angular ships with a component decorator to use it in that file you need to import it though so import component from at angular core now this is one of the packages the angular framework is comprised of and this package includes these core features like that component decorator which you attach to a class to mark it as a component which angular then scans for certain features and uses as a component now the component decorator takes some configuration in the form of a javascript object which we pass to it in that object we need to define things like the template so we define a template and if we just use template you could pass a string in here to write some html code here but for longer templates this is not really something you want to do define a template url instead and then add a relative path to your template file so in my case it's post create dot component html so this is then the file while angular will look for the template and then parse so now this is pointing at that html file now with that we also need to add more we want to add a selector let's actually add that first a selector which allows us to use that component so to use it by that selector which serves as our own html tag the convention is to start with app dash to avoid clashes with normal html elements which name you might take otherwise accidentally and then any name you want but typically you also use the well file name or the component name for this so app post create don't forget the comma now this defines a basic component you need a template and you typically also need a selector so that you're able to include it you don't need to add anything in the typescript code here we want to add something in the template so that we can see it maybe a h2 tag the post create component and now what now we could use it we could go to the app component html file because remember all components other than the app component are added to other angular components not the index.html file and in the appcomponent.html file we could add app post create like that this is now our own html tag our own component being used you see my ide already isn't liking this and if we save that and we go back to the application we see a blank screen if we now open the developer tools here in the browser we see that we got an error message that app post create is not a known element the reason for that is that it isn't a known element angular has no way of knowing this because by default angular and also not the build process it doesn't scan all files in our app folder and try to evaluate if it should be aware of that if that is a component instead we explicitly have to register a component if we want to use it and we do that in an angular module in the only module we get thus far in the app module there we add it to declarations and for that we first of all need to import it that's a typescript requirement if you use something in another file you need to tell typescript where the code behind it can be found so we want to import something from posts slash post create slash post create component and you omit the extension so you don't add dot ts here now the something we want to import is the post create component class so a reference to the class to be precise and we store that in the declarations array here so that now angular is aware of this and that is all we need to do now if we save that you see the post create component here and the errors in the ide will also go away as soon as you change something in the respective files and then save again so now we get our first component added that's nice it's not that useful though would be nice if we could use that component to really well create new posts so let's do that in the next lecture we want to create new posts and we got the post create component thus far it only got a title well what do we need to create new posts as a core minimum we need an input and we need a button to save that post right so let's add both in the template of post create a input a normal text input or maybe a text area because we want to be able to enter more text in just one line so let's add a text area now we don't need a name we can omit the id columns we don't need that rows i'll set this to 6 so that's a bit smaller and if we save that we see a text area no styles so it's not that pretty we'll come back to the styling soon let's focus on the logic for now as i said we also need a button so let's add a button below the text area where we say save post like that and now of course this doesn't do anything it looks super ugly let's actually do something about that let's add a horizontal line between the two for now but it's still not pretty but we can work with that so we can click that button but it doesn't do anything we can enter anything here but that of course doesn't create a new post because what's missing the logic well also the styling but mainly the logic how would the browser know what we want to do when we click save post it can't and that is exactly the logic we'll add with angular now to do something upon a click here we need to add a click listener and we do that with a feature called event binding event binding is an angular feature which allows us to listen to events in a declarative way which means instead of using javascript where we would go to our code and then try to select the element with query selector or anything like that and then use add event listener on the element instead of doing all that programmatically we go to our template and we add something there which is not default html but which is understood by angular since this is an angular component we add parentheses and in between there the name of the event we want to listen to and that's now not on click but just click so the name without on and you can of course also listen to things like mouse down mouse enter and so on but here it's click then equal and then quotation marks between which you define the code you want to execute now that can't be complex code here in the template and typically you just pass the name of a method of that component class here which should be executed so we could add a method that's a function in a class to that post create component and i'll simply name it on add post the name is up to you but you typically start with the on at the beginning of your method name for methods that are triggered upon events now in there we want to get information about that new post right and for now what i'll do is i'll just throw an alert post added so that we can see if that worked if we successfully triggered this now i pass this on add post function name here including the parentheses to click what this will do is it will connect both after reloading for click save post we see that alert up here so that worked now that's the first step we are able to listen to events we're not able to get the input we entered here and we're not able to output anything on the screen other than that alert these are the things we'll work on next so before we come to fetching that user input let's output a post let's output some dummy content let's say we have a paragraph there below the button and here we want to output the content the user entered now for now the user didn't enter anything so let's set some dummy content for this we need two things we need to set some content in on ad post and we need a place to store that content in which we then can also refer to from the template that stored the content in thing is a property basically a variable in a class you define it without the var const or let keyword you just add the name in the class here and the name can be anything you like like for example new post now i'll set this to an empty string by default and then on add post i will overwrite it we refer to it with the this keyword this new post and we set this equal to any content you like like the users oops escape that post like that notice that i escaped that in between single quotation mark with a backslash so now we're setting the new post value to this value whenever we click the button now to output the new post we need to go back to the html file and just as we added the listener directly in here we also add output or output hooks directly in the template we do that with a feature called string interpolation and you add or use that feature with double curly braces opening and closing and in between you refer to something which is stored inside your post create component or your component belonging to the template in general that something could be a method and then you would output whatever this method returns or it can be a property name like new post so here i can just say new post and refer to that property and now what you can see is that when i save this you don't see anything because we start with an empty string a new post but if i click save post you see the user's post here because we changed that text and due to string interpolation we told angular hey please output the current value of the text and also when it changes please output the new value in this place here in our html code so that is string interpolation in place and that is one important building block when it comes to outputting content now let's also dive into one other way of outputting content on the screen let's say we want to pre-populate the text area with some dummy starting text let's say we don't start with an empty string here but with no content now of course if i save this it reloads and we have no content here until we click the button and let's say we want to output no content in the text area too now in the text area we can use string interpolation like this new post and if we save that we get no content in there too we could also do something different a text area is an input element in html and as such it has a special property we can bind to not an attribute a property html elements in the dom and in javascript are just javascript objects with a couple of properties so variables belonging to that object which we can read and write and one property is the value property now the value property actually can't be set like this so if we set this to test here you see it's empty but we have another feature in angular which allows us to directly target properties of the underlying objects of the html elements we can add the property name and of course you have to know that this element has a value property but now you do know you can use resources like the mdn the mozilla developer network to get complete references of all available properties of all available elements but if you know that name you can wrap it in square brackets like this and this will now directly target the value property of the underlying object and bind the value between quotation marks to it now important just as for the click listener or for string interpolation this value is now not normal text but actually typescript code so if you enter test here it would look for a property named test in your component if you want to output test as a string you need to wrap this in single quotation marks and now if you save this you see test as a starting value because we're binding to the underlying value property and of course you can also bind this not to a string but to new post now without the single quotation marks because now we want to refer to that property in our component class and now we see no content there too this is important to know we will use a combination of string interpolation for a simple text most of the time if you want to output it between opening and closing tags and property binding always used directly on the elements for outputting data in our template now we can output data that's all cool but how can we now finally get that user input we'll do this in the next lecture so let's get the user input and there actually are two ways of doing that the first one is another feature which is called local reference we can add a marker a variable to any html element we want we do that by adding a hashtag and then any name you want like post input like that now this marks this or it creates a reference to that element which you can use and which you can use and that's important in that template so you can use it for example here to pass data to on add post you could refer to post input like this without the hashtag now and then pass this entire thing so this will now just be a reference to the underlying javascript object in all add post we can take a look at it by expecting it as an argument so there we get the post input and this will actually be an html input we can clearly tell typescript to type by adding a colon then html text area element that is exactly what it is now this just informs typescript about the type here this is great because now we get better auto completion because the ide knows which kind of type that is but it also helps us write cleaner code but i of course only want to do one thing here i want to output the post input like this if we save that and let it reload and have the developer tools open we see that upon saving i get this output now we can't really see what's in there we can't really see the javascript object we can look into that with console.der instead of console.log now if we press save content we get the text area object and here you see all the properties this specific javascript object knows quite a lot as you can see there also is the value property we bound before now of course we cannot just bind the value property since we got access to it here we can also just use it to extract the content and set the content we entered as a value for new post so we can say input dot value to access that value property and now if we save that what we can see is that if we enter something here and i hit save post we see something down there now that really is amazing and this allows us to fetch the user input and output it it's only one way of getting that user input though this is a way which of course allows us to do anything with that element not just get the value but then get the value if that is what we want to do upon a click now another feature angular offers is a feature called two-way binding rather than manually setting the value of the text area and then also getting a reference to it and so on we can get rid of both and actually add a new feature which combines the setting and reading of a value it's called two-way binding because it has this two-directional flow and you add it with square brackets and parentheses and then ng-model in between ng-model is an angular feature it's a so-called directive a directive is basically an instruction you place on an html element in angular or you can also create your own ones so the directive knows what to do on that element then ng model is a directive that actually will listen to user input and emit that data to us and also store new data in that text area or output it there we need to bind it to a property and i will use a new property for that because i don't want to update new post with every keystroke i'll add entered value here it's an empty string initially and entered value this new property is what i bind to ng model now important ng model by default won't work it's a feature which is not included in the core angular package here it's not included in the browser module which we already added it's included in a different module which we need to add it's included in the so-called forms module because it's related to forms inputs and this is part of add angular forms so that's still part of the core framework but of a different part of the framework so importing it here allows typescript to find it angular isn't aware of it yet though it is aware once we add it to the imports array in our app module now we're unlocking some forms features and ng model is one of them so now we can use ng model here and it will automatically update enter value or entered value here with every keystroke and therefore in this new post we no longer receive the post input here instead we simply set new post equal to entered value this entered value back in the template this also means we get rid of post input as an argument here and now if we save that and we go back to our application you see we don't start with no content anymore i can enter something and if i hit save post we see that here too but now we're using that two-way binding feature which can also be very handy these are the core template binding features angular has event binding string interpolation property binding which you sorted before with square brackets value and two-way binding with that we got a lot of tools that allow us to manipulate our components and the output we have and also to react to user events and now with that it's time to leave that world of ugly applications and actually turn this into a pretty one and dive deeper into really building a mean stack project because this is of course no angular basics course but knowing all these basics and refreshing them is really important so that you don't get lost throughout the rest of the course so now that we had this brief refresher on the very basics of angular it's time to work on the real application we're building and we want to build a beautiful application right now we could write all these css styles on our own and write everything from scratch on our own but this is an angular or especially a mean stack guide and i want to focus on these mean stack components and not so much on the styling therefore i'll use angular material which is a package actually also created by parts of the angular team which gives us a set of pre-built angular components and that's important it's not just a styling package it's not like bootstrap it's actually an angular package which ships with a couple of angular components which we can drop into our application now we'll still write all the core logic of our application on our own but all the nitty gritty details and to be honest quite a lot of the styling will be taken care of now this uses google's material design so of course you have to like that to be happy with that but i think it looks quite nice and if we have a look at the components part on material.angular.io we can see it has a bunch of pre-built components that should give us everything we need to build a nice application to include things like a header include things like our buttons our inputs things like that so this is what i want to work with and to add it to our project i'll quit my development server for now and i need to install this so we'll run npm install dash dash save this will install a new dependency into that project npm is that package manager and now it's add angular slash material now don't hit enter yet this is one way of adding it now if you're using the latest cli version which you very likely are cli version 6 plus to be precise then you get a different command available and if you don't use the latest version you can always update by running npm install g at angular cli by the way so if you use that latest version and your project was created with the latest version 2 you can run ng add now that's the cli command at angular material and what this will do is it will also install the material package but also already configure your project to include it and i'll of course show you what this means what included actually means and by the way i also got a series on youtube and my webpage which you can check out you'll find a link to it in the last lecture of this module where i give a little bit of a more detailed walkthrough of angular material i also got another course here on udemy where i dive deeper into it in this course this will not be an angle material course i just want to use it and i will therefore just explain the basics you need to know about using it so now it's done setting it up and what it did is in the package.json file it added a new dependency or two new dependencies to be precise angular material this package and the angular cdk now the material package actually split up in two packages you could say one for the logic behind the components and one for the concrete implementations and the styling the cdk is the logic material is then logic plus styling and more on that in that series i just mentioned this is included this is installed as a dependency in the angular json file which configures our project it also did one thing it added this input here this style m here which simply includes a default theme of the material design package indigo pink so that's just some colors that's the styling for all these components and you can actually switch that with another pre-built theme you can see all of them in node modules at angular and then their search for material here and then in material you should find a folder pre-built themes this one and there you see four files indigo pink deep purple amber and so on now we're using indigo pink here and you can always switch this so you can all use purple green deep purple amber i'll stick to this one but you can switch this with one of the other files so this is the styling that is added now what else did the ng add command do for us it edited our app module there it now imports the browser animations module a part of the angular framework because some of these components provided by angular material use animations and therefore this is included too and that's basically it you can also see a log of what it did here so it updated package.json angular json app module styled css now also the index.html file there we can see what it did is it included imports to the material icons so that we can use these icons and the roboto font so that our text actually has the normal material design too so that is what now happened now we can restart ng server we can start using angular material and to use it we actually just need to import what we need and use the component in our template so first of all let's start by pimping that post create component and for that let's look at form controls in the official docs that sounds promising and what we need is some some input right we need some inputs we want to be able to add a text area so we got our input and text area elements which you can use and here if we check out that example code we can also see how such an input is created with the angle material package essentially we add this matte input thing to a input element we can ignore that form thing for now so let's go back to our project and to use such an input element we need to unlock it because by default none of the components provided by angle material is available in our application and this is done to save space that our final application is as small as possible and we don't import things which we don't use now i want to use something of course so let's actually move that import here up to the top to keep all the angular imports in one place and then let's import something from at angular material and that's something i want to import here is just a module it's the matte input module now we can take that module and add it to the imports array and what this does is it unlocks all the input related components so now we can go back to the post create component html file and there the text area we simply add matte input to it this is the selector which turns this into angle material input now let's save this and i don't see a big difference to you now the reason why we don't see a difference is that actually all these input components only work in conjunction with another well component we have to add as a wrapper and that's the matte form field component now that's just another component provided by angular material and we put our inputs in there now i said we don't have to worry about that foreign thing and we don't we won't use a forum yet but this is something we need to add to get a styling that looks better so now we can see angular material seems to do something we don't have that ugly input from before now it's also not super pretty yet but we'll get there to turn this into a prettier component what i'll do is i'll use another component from the angle material framework and that's the matte card so let's add another import in the app module matte card module card is a special container a look you will probably know from other pages let's add the matte card module to the imports array and then in the post create component i'll wrap my mat form field here with matte dash card now this creates such a card look if i put it in there and we save that you will see now it's indented a bit more and you see there's a slight shadow below that now we can't see it that well because a bit hard to see it's taking up all the width so let's restrict it with by also adding some custom styles to that we can still do that i'll add a new file post create component.css for the styling for this component and we need to import this by going to the typescript file of the component and adding style urls here now that's an array of external stylesheets we can only have one template but we can have multiple styles and there a point at post create component.css now we can write our own css code there and i will target my matte card element that's cool we can use the angular selectors here as style targets so we'll target matte card here and actually restrict the width to let's say 80 percent and add margin auto to center this now if we save that now we can see the card here a bit better and we got our form field in there and if we type you see dissolve form field now this is taking shape now i'm still not perfectly happy with that i also want to change the look of my text area a bit more so also target my text area in that component and the cool thing is these styles will be scoped to this component so even if we use a text area or a matte card in another component these styles will not apply to it it will just apply the styles to the elements in this component so i'll take my text area and set the width of it to 100 percent here actually however for this to have an effect i also need to take the wrapping element matte form field and give that a width of 100 and now if we save that you see the input is spanning the entire width here and now i want to put my button into the card too so i'll take that button put it below that mat form field remove the hr tag here and of course it would be nice if the button would look prettier too so we can turn it into a material design button by including one more thing from the angle material package the matte button module here and i will add this down there matte button module so now we're including the matte button module and now we can go back to our html code and turn this into a nice looking button by adding matte button or matte raised button to get this raised button look and you can find out which values you can use of course in the angle material docs in case you want to dive deeper you can always dive into the docs read through them check the api documentation for a full list of the features you can configure things like that so now this is the button now it would be nicer if it has some color and thankfully if you check out the docs you find out that you can add a color property i'm just splitting this over multiple lines to make it easier to read so here i will add color and you can set this to primary or accent or worn now word is some warning color red don't want to do that i want to use my primary color whoops primary and now this will use the indigo color in this case because i'm using the indigo pink theme you can of course all use accent and maybe i actually prefer this i think it's even clearer to see so now we get the button we get the input here now this is looking prettier now it's time to add a toolbar and then also add a real posts management because right now we're not really adding new posts we're just overwriting some text which we output time to change that let's start with the toolbar because i think every application has some sort of header and i'll actually create a new component for that so not on the posts folder but in the app folder itself i'll add a new folder header and in there i want to create my own header component so i'll name it header.component.ts and add a header.component.html file you learned how we create these components so go through that a bit quicker export my class header component in there and add the add component decorator which you need to import from at angular core my ide automatically added the import you might need to do that manually depending on your id add a selector i'll name it add app header and then also add a template or a template url and here i'll be pointing to my header.component.html file now that's the header component typescript file in the html file i will use yet another component provided by the angle material framework so in app module we need to unlock that first here to our import list from add angular material i'll import yet another module the matte toolbar module now as you probably can guess this unlocks a certain toolbar component to unlock it for angular we need to add this to our imports array and now we can use the material design toolbar let's quickly check out the docs there on the left you find toolbar and you can check out the demo code as you can see it's really easy to use not that difficult you can configure a lot though again feel free to read through the entire documentation here so i will add it in my header component toolbar and we can for example set a color which i will set to primary because i don't like that boring grayish look and there for now i'll just set my messages as a title so to say now the header component isn't used yet to use it we first of all need to unlock it so we go to declarations in our app module not imports because we're not importing another module we're just importing another component in our case and there i will add my own component so i'll again let my ide automatically import this and i will just add header component and my ide adds the import up here this is important so now this is added now we can use the header component here and i want to use it in my app component instead of our first app i'll add app header like this now with that added here let's save this let's go back to our application and we get this nice toolbar above the rest of our application now the card is sitting directly on the edge of the toolbar to change this what we can do is we can simply wrap our main content with the main element now that's a normal html element put our post create component in there and now style that main element directly here the app component css file maybe and you can of course also use css class selectors you don't have to always select the elements so here i will give this some margin to the top of let's say one rem or 16 pixels would be the equivalent uh whichever unit you prefer i will work with rams here so now we get some distance between the card and the toolbar now the thing that is missing for now we'll add navigation later the thing that is missing for now is a way to output the posts it would be nice to output the posts below our input area here so let's do this next so the goal is to be able to output the posts and for this i'll add another new component because i said you want to be granular and creating a post is actually something which is decoupled from outputting the posts so in the post folder i'll create a new subfolder which i'll name post list and in there i'll add my post dash com file and the post list.component.html file for the html content now you know how to create such a component by the way if you use the cli regularly for that you can also create components with the cli with a command i'm a fan of the manual approach also because it's really good for practicing so here i'll export another class post list component and as you know we add the add component decorator to it and in there we add a selector this will be app post list and a template url link where we point to our post list component dot html file so now we got that base component set up as you know we need to include it to app module to use it so in the declarations array i'll add my post list component also add the import here my ide added it and with that we can use it in the app component maybe below the app post create component there we could add app post list like this now right now our component is empty the goal is to render a list of posts in there so for now first of all let's go back to post create component and get rid of that ugly paragraph and then dive into the post list component html template i want to use another feature of the angle material package and that can be found under layout i want to use the expansion panel which is a collapsible well panel where we can display some content now to use this i'll go back to the app module and import one additional module from angular material the matte expansion module and also add this to the imports array here mat expansion module like this and now with that added let's go back to the post list component html file and to use it we can again have a look at the official docs at the dummy source code there as you can see they use the matte accordion to wrap this all this is used to basically be able to orchestrate all these expansion panels now we can easily recreate this by adding matte accordion here as an element in our post list component html file and in there add the matte expansion panel element and in that matte expansion panel element you can have a matte expansion panel header this allows you to define a title and below that header you can also have some regular content like here i'm in an expansion panel like this and this would be the expansion title now if we save that and we go back to our application we can see our expoundable element here now it's sitting directly beneath the card at the top here which is not super pretty additionally i'd also like to restrict the width of that since i want to do restrict the width of both the input and this maybe i want to restrict the width of the total main content so let's go actually to the post create component to the style there and i will not set matte card here anymore to have a width of 80 percent instead i go to my app component css file and for the main area here there i will set a width of 80 percent and margin auto for now so now both is limited in width and centered now to have some spacing between our post list component and our post create component we get multiple ways of achieving this one simple way is to add a margin top to our post list component and we can do this by adding post list component dot css here and import this into our post list component by adding style urls here post list component dot css and in here then target a special selector the host selector which targets the element itself so to say and add a margin top of one ram and if we save that nothing changed because actually all the elements by default are not treated as block level elements so we have to set display to block first once we do that now we get some spacing here cool so now this is working now let's go back to populating this with some content too we get a title and our well content so we might want to add a new field for a title here eventually but first of all let's see how we could output a list of some dummy posts so back in the post list component we only got one expansion panel with hard-coded content in there now let's say we had a list of posts so the post list component let's say we have posts and this actually is an array and in there we got some javascript object where every post has a title like first post and some content like this is the first post content and we had not just one but three posts so the second and the third post and here we got the second posts and the third post content now would be nice if we could dynamically loop through all these posts and output that data in our template right now actually angular has us covered when it comes to this it offers so-called directives which i already mentioned before briefly which allow us to manipulate elements in the dom when needed now let's dive deeper into what i mean with this and how this works in the next lecture the last lecture we added our expansion panels and now we get some data here and that's a typical use case right it is also what we will have at the end of this course you fetch data from some backend from some server a list of posts a list of users whatever it is and you want to output this in your template therefore you don't know in advance how many elements you're going to need we only got one expansion panel now we would need three and we don't want to hard code our content in there anyways so we need some way of dynamically looping through that code and creating as many panels as required and we can do that with the help of a so-called structural directive angular ships with directives which as i mentioned before are instructions you place on an element and there are some instructions that only apply to a single element ng-model was one of them but there also are instructions which structurally change the rendered html code and that's the case here we can use another special directive ng4 and you add with star and g4 the casing and the star is important and this is essentially a helper tool that allows you to repeat an element as often as required now the as often as required part is defined here between the quotation marks after the equal sign here you write the looping logic like this you add let to create a variable let post in our case this name is totally up to you off and then the data you want to loop through so here it's this post's name so this is now not up to you or it's up to you but you have to change it here and in the component if you change it and now we're looping through all the posts and we're storing the individual post in this post variable which is created here and now the cool thing is we can use that variable in the template here we can output post title here for example and down there we can output composed content like that and now it will create as many expansion panels as we need and give us access to the data we're looking at and now if we save this we get three expansion panels for the different posts and you see by default only one of them can be opened if you want to allow multiple ones you can add multi and set this to true on the accordion now you would also be able to expand more than one post at a time so this is now our accordion with the posts and this is how we can render data a list of data dynamically with the help of ng4 now of course we don't want to use hard-coded data we want to use data which we actually receive from well the post create component in our case here and to do that i'll get rid of my dummy data here i'll actually comment it out so that we still have it for reference but i'll set post to an empty array now and this is an empty array and if it is empty well then we actually don't render anything maybe we want to show a placeholder and we can use another structural directive for that so back in the html template we could say we only want to render this accordion here with all these posts if we got posts so what i can do is i can check with another structural directive which with ng if if a certain condition is true and only if it is true only then this part on which ngf sets and all the child components will be rendered and that's important it's not hidden if it's not true it's not part of the dom it will only be added to the dom if this condition is true and what is the condition anything you want so you can refer to a function here which returns true or false to a property that stores true or false or write a short code snippet here i'll check if post's length is greater than zero and if it's not then this will not be rendered in that case i want to render something else i want to render a paragraph where i say no posts added yet lowercase p and i will add ng if to that 2 and here i will check if posts length is smaller or equal to zero then i will render this fallback text this is why we see no posts added yet here now this clearly looks super ugly thankfully we can change this with some built-in css classes you can find more under guides and they're using angle materials typography here are some classes you can add and there i will add body one as a class here matt that's always appended at the edit at the beginning matte dash body one and now if we save that we got a nicer look now it has the roboto font for example and if we want to center this for example well then we can also add another class because i don't want to style all paragraphs i just want to style this paragraph so this will be my info text and i will target this now in my css file info text and simply set text align here to center and now we're using some structural directives to present a nice user interface time to be able to finally add some posts and connect the post create component with the post list component so would be nice if we could add posts right and to be able to do so we first of all need to add one more input field to our um well post create component right now we only got the text area i will actually add one additional one mat form field here and in there i'll add a normal input for the title now important to turn this into a material input field we have to add matte input and this now well as i said should give me the title i want to add so here i will for now also use two-way binding i'll rename this to entered content and i will have the entered title queue we can also get rid of new post also down there maybe swap position steer to have the title first go back to the template and use entered content here and on the first input use ngmodel and two-way binding to bind this to the entered title so now this is all up to date now we can create a new post in on add post store in a constant because we're not changing it new javascript object where we have a title property and where we store the entered title and where we have the content property to store the entered content and we can also structure this over multiple lines to make the bit easier to read i guess now the thing is this post is here that's cool how do we get it into the other component we can use this property and event binding thing you learned about with the click listener and so on we can use that on our own components too we can emit our own events and we can also send data into a component and we want to emit an event here in post create we want to emit and hey i got a new post event and we want to listen to that event in the app component which is where we were using the post create we then want to get the created post add it to a posts array which we probably managed in the app component then later and pass that post array down to app post list so step by step let's first of all go to the post create component and emit our own event to emit an own event we need a feature provided by angular core the event emitter then we add a new property and that property here can have any name you want so i'll name it post created it makes sense to kind of use your event name as a property name here and that will be a new event emitter created with the new keyword and now with that we can go to on add post and call this post created and then emit to emit a new event now here we wanna pass our post as an argument that's important so this passes the post as an argument cool so how can we listen to that well we first of all have to make angular aware that post created is an event to which you can listen from the outside whilst it makes sense to be able to do that because you really want to listen to events you emit in the same component you still have to do this explicitly and you do this by adding a decorator to this property this decorator is called output so just like you added add component to the class here you now add add output and don't forget the parentheses to post created this turns this into an event which you can listen to from the outside and from the outside means in the parent component so in the component where you're using the selector there we can now use event binding to listen to post created and then again execute any code we want whenever this event occurs and of course what i want to do here is i want to get that post and store it in a list of posts so in the app component here i'll overwrite title here with a new posts property which is an empty array initially but then here i'll add onpost edit as a method as a function so to say and we know that we will get a post as an argument here and it will therefore set this post or call this post and call push here and push this new post on this list to store it there now that's one part now we're adding this post here of course this doesn't do that much we also need to be able to pass this post down or first of all let's connect post created with on post added so the method name you chose here and to pass on the data you're getting you have to use a special variable name and that is dollar sign event this essentially gives you access to the data you emitted and that's not just for custom events that would be the same for click events or any built-in events too there you also get a default dom event object whatever you're passing or receiving with an event you get access with the special dollar sign event variable so that you can pass it on to your own method or use it in an inline code statement you might have here so now we're passing this on now we need to pass it down to app post list and there we can dive in we got our posts all we have to do is make the posts property bindable from outside wire property binding by default it's not bindable but we can make it bindable by adding a decorator to it and since we had at output for emitting an event it probably makes sense that here we use input and this is added with the add sign and then the name of the decorator input and don't forget the parentheses now you can bind to posts from the outside and from the outside again means from the parent component only from there only from the direct parent so here we add square brackets for property binding posts and we can set this equal to posts here now to avoid confusion about the names i'll actually rename this here i'll name this stored posts so stored post is the new name and i will pass this on here and now the chain is as following we're listening to the post created event we're adding the post in on post added to our stored posts list and we're passing down that list that array to app post list and angular's change detection will automatically detect whenever a new post is created when that changes and when it needs to render this new post so with this we should have a complete chain in place that actually allows us to enter a title here and some content here click save post and see that being added here and of course we can add another title and even more content and continue creating new posts so that's pretty amazing this is how we can create our posts here and how we can add them with the help of property and event binding on our own components we get that working chain where we add new posts and output it here now it's time to make our first little optimization as you might have seen we are using posts in different places we got our list of stored posts here in the app component we're outputting posts obviously in the post list component and we're creating posts here now we ensure that they always have the same structure title content we do this when we create them and we rely on this structure when outputting them we're referring to post title post content so a mistake in the creation would not be that good additionally here in the app component we actually just say we have an array we could store anything in here we could store numbers in here and of course we are writing our application we probably don't mess up on purpose but if we're working in a team or if we're coming back to that application after some weeks or months we might have a hard time figuring out immediately which kind of data we stored there was it post dot content or post dot description so it makes sense to create some models so basically blueprints contracts which define how a post looks like in our angular application and i'll do that in my posts folder i'll add a new file in there not a folder just a file and i'll name this post.model.ts so it's a typescript file and in there i'll use another typescript feature a so-called interface an interface is like a class that defines how our object looks like but it can't be instantiated it's more like a contract we can use it to create our own type to force a certain object to look like this even though we can't directly create it based on the interface and here i'll name this post now we create it like that and in there what we can do is we can now define the fields and methods this should have and i want to have a field title which should be of type string assigned with a colon and i want to have another field content which should also be a string and this ensures that we got a clear definition of how a post looks like in our application now of course an interface in this file isn't that useful so i add export to make it available outside of this file too and now we can import this in all the files where we're using this so in the app component for example we can now add an import import post from and then simply go to posts and import it from that post model file without the extension as always and now we can say that stored posts is an array of posts by adding a colon here and then post square brackets this is typescript syntax for saying we got an array of posts in there and now if we would try to add a free we actually get an error that a free is not a post so this is pretty cool we get a warning here we would also get a warning if we try to save this and compile this of course we got other places where we use the post too in the post list here we got another list of posts so here it's the same thing we import post from go up one level post model and then assign a type here and say we got a list of posts and finally in the post create component there too i want to import my posts type so to say from post model post model like this and then whenever we create a new post this will actually be of type post we can be very clear about this and we can even be clear about the data we're going to emit event emitter is a so-called generic type which simply means we can pass additional information about which type of data it works with and the event emitter works with data in the sense of it emits data and that data will be opposed so we can add lower than greater than signs that is how you define such a generic type post now we're saying data we emit will be a post and now we're pretty safe because now if we ever try to emit different data or do something else we would get an error and therefore now we can come back to that code and quickly see how a post looks like it's all the time for one hour improvement when creating posts right now we're doing this with two-way binding and it's not necessarily wrong but angular also makes it easy to work with forms and of course it makes sense to all the user forms semantically so what we can do is we can add a form element normal html element in our card here in the postgreat component and wrap the form fields and the button with it like this and unfortunately it removed my multi-line setup here let me recreate that and now in here i got my different inputs in that form and now we don't need to use two-way binding anymore though we can we can use another mechanism angular provides when it detects a form element and we get the forms module included which we do it will automatically create a javascript object behind the scenes which represents this form so to say where we can easily register inputs as controls of which it will keep track of where it will then store the values of these controls and where we can easily add validation to and submit the form and use the value of that form for that we can get rid of the two-way binding here with this syntax and instead add ng-model like this so as a directive without any bindings this will register this input as a control to this behind the scenes form however angular needs to know how to name this input so we need to add the normal name attribute and give this any name of your choice i'll name it title and the same for the text area we can use ng model we need to add a name now so i will name this content maybe all the reduce to rows but that of course is optional and now angular is aware of these two controls on this form now when we click the button i don't want to call on add post manually anymore instead i will set this button to be of type submit because we're now in a forum and the default html behavior is that a button with type submit in a form will submit that form and submitting will trigger a special event to which we can listen to the submit event and that is where i want to execute on add post like this now on it post remember is our method here so now we're doing this whenever we're submitting the form and angular will also prevent the default which would be that the form gets sent to the server we don't want to do that we want to handle this entirely in javascript now with that we get the form here now we need to get access to the values inside of that form and this can be done with the help of a local reference we can add a reference to the forum and you can name this however you want like post form and now important you don't just add it like this this would give us access to the html element object we can actually assign a value here and that value has to be ng form now that is a directive angular implicitly attaches to the form element here for us and what this strange syntax does is it gives us access to this object this form object angular created for us and manages for us behind the scenes so now post form gives us access to that angular form object and we can pass post form as an argument to on add post and then on add post we now know that we received the form which actually is of type ng forum which you automatically or what you import my ide does it automatically from at angular forms so at angular forms this gives us access to ng form and this now actually holds a lot of information about the form for example whether it's valid or not but it also gives us access to the values of the form on the forum there is a value property and on that value property we can access things like title so essentially the names we defined here title and content so foreign value title gives us the title the user entered forum value content gives us the content obviously now it's possible to enter invalid content we can submit an empty form and we add an empty post therefore clearly not what we want we can easily add validation by adding some default html5 validators to our inputs so this is not angular there is a required validator for example now what angular will do though is it will automatically detect this and then run some behind-the-scenes logic and javascript to also update its form object to reflect whether it's valid or not so if it fulfills our html5 validators so i will require both you could add more for example there also is a min length validator where you could say the minimum length of a title is free and not just one as it is with required these are things you can add now we got the validators in place and now angular is aware of the fact whether the form is valid or not that being said whilst this is the case we can still submit an invalid form if i hit save post you see it actually marks them as invalid by underlining them in red that's the angular material feature but it still submits it if we want to prevent that we have to do it manually in on add post we can check if forum invalid and if this is true then we just return what this means is that now if i reload and click the button no post is added but it still tried to submit it but now it marks it as red and now thanks to angular material we can also easily add beautiful error messages if we go back to angle material and there to the form field there on the right you can click on error messages and you see there's a special matte error component you can add below the input let's copy that into our post create component input here so below the input i add this and we don't want to check email here there we want to get access to that input more on that in a second but we can check whether this is invalid and then well display an error message we'll also have to change that so what we can do here is first of all we need to get access to that input and there are two ways of doing so we can reach out to our post form and there call get control then pass the name between quotation marks and get access to the control like this or we add a local reference to that input any name you want like title and set this equal to ng model so where ng forum gave you access to the entire form this gives you access to the well data managed for that input behind the scenes and then you could also say title invalid because now this is the form control behind the scenes now whatever you want to output here can be dynamic content but it can also be some hard-coded text like please enter a post title now i'll just copy that matte error and also paste it below my text area here and on the text area i will now also add a local reference content equal to ngmodel here too and therefore here we check whether the content is invalid and now with that if i save that and go back to my application and i submit this you see we got the error messages below the inputs too this is really cool if i do enter some valid information here i can submit so this is form handling with the help of angular forms so called template driven form to be very precise because everything is inferred from within your template there is an alternative to which i will come back later so template driven forms and a little help of the angle material package when it comes to beautifully handle errors now one thing i noticed is that i accidentally removed my margin here at the top because i set margin to auto well of course we can fix that by adding one ram here on the margin to top and bottom actually and then audit left and right that's a quick thing and that's not the main thing i want to focus on here instead what i want to focus on is how we get new posts from the post create component to the post list component here right now we get this chain of property and event binding we're emitting a new post here and we're passing it to the parent component and then we're passing it down to the post list component and this clearly works but i guess you can imagine that in bigger and bigger applications this becomes more and more cumbersome because you got longer and longer chains of property and event binding to get an element from component a to b to c to d to e and that is not really what you want to build typically so it would be nice if we had an easier way of passing data around or an alternative at least and such an alternative which we will use quite a bit throughout the course for other things too is a service a service is a class which you add to your angular application which you let inject by angular into components i'll come back to what inject means and which is able to centralize some tasks and provide easy access to data from within different components without property and event binding i will create a posts service in the posts folder by creating a new file posts dot service dot ts and that name is up to you but the convention is to name it dot service ts now a service is just a typescript class so export a class posts service just like that now in there i want to store a list of posts so i'll add posts and set the type to post array now for this i need to import my post model so i import post from dot slash post model like that and this array initially is empty let's say you could also set it to undefined but i'll set it to empty now here i actually want to turn this into a private property which means you can't edit it from outside i do this by adding private in front of posts now this post service if we add to another file can't access posts instead i will create a new method get posts which allows someone who's interested to retrieve the posts so in here i will return this post so i can do this because now i'm accessing the post from inside but i actually don't want to return the original array because as you might know arrays and objects in javascript and also in typescript are reference types and if you don't know what reference types and primitives are an article and a video i created can be found in the last lecture of this module it's really useful for understanding this essentially a reference type is a type where if you copy it you don't really copy it the object in memory will stay the same you just copied the address so the pointer pointing at that object so to make a true copy of the posts i will use a typescript and next-gen javascript feature called the spread operator i add square brackets to create a new array and then three dots to take all the elements of another array the posts array here pull them out of that array and add them to this new array so i'm creating a new array with the old objects and therefore this array has been copied important not the objects these are still the old objects but at least the array is copied so if i now edit this array if i add new elements or remove elements from within another component this will not work this will not affect my original array here so that's a little bonus you don't have to do that but it's a good practice to do that to try to be immutable be clear about the fact that you don't want people to directly edit this posts array and with that we get a get posts method getting posts is nice but posting them would also be nice right so i will also add a add post method where i expect to get a post as an argument you could also just get a title and some content and then construct the post here whatever you prefer i will do the latter so i will create a new post here a post is of type post and it's a javascript object which has to have you know a title because that's defined in our post model and it will store the title there and a content property into which i will store the content argument and now we can reach out to our post here or to our posts array and push that new post into it now if we do that we added this post and now we get methods for getting all posts and for adding a new post now we could use that from both the post list component and the post create component without having to pass data around with property and event binding for this we just need to get the service into these components and this is done with a feature called dependency injection now this means that you simply go to the component where you want to use that let's say to the post list component and you add a constructor you do this with the constructor keyword constructor simply is a function which is called whenever angular creates a new instance of this component and here you can expect arguments but since angular is the one creating new instances of the component angular has to give you these arguments and angular has a complex dependency injection system which is able to actually find out what you wanted and indeed give you that so here what you do is you define the service you want to have and i simply add an argument with any name you want i'll name it posts service though because that is what i want to have and now you have to define the type here to give angular a hint about what it actually should give you so here i'll set the type to post service and i need to import this so i'll go up there and import postservice from posts dot service like that now this will actually tell angular hey i want to have a post service instance because you set the type and angle will try its best to give you an instance of the service however i also want to store this in a property of my class here so i can add a new property here which i can also name posts service which is of type post service and is empty at the beginning and then here we can set this posts service equal to the post service instance i'm getting here now this is a bit of cumbersome typescript offers a shortcut for this we can omit all that code and actually get the exact same result by adding a keyword in front of post service the public keyword will automatically create a new property in this component and store the incoming value in that property now that's all nice and angular will try to fulfill this requirement but actually it won't be aware of the post service because it doesn't scan all your files so you have to make angular aware and there are two ways of doing that you can go to app module and add the posts service there not in declarations and not in imports but in the providers array providers are for services there you could simply add posts service and also add the import pointing to that file and then this would allow angular to find that service that's option number one and there's nothing wrong with it you can also take an even easier route and go to the post service and add an argument to it at injectable which is imported from at angular core don't forget the parentheses and there you don't have to but you can pass a javascript object to configure this and you can then set provided in and set this to a string named root or with the content of root and make sure to not mistype root as important and this simply will do the same it provides this on the root level and this not only means that angular finds this this also means and the same was true if you added it to providers that angular doesn't only find it but that it will only create one instance of the service for the entire app so wherever you inject this you're going to use the same instance and this is really important because since we manage our posts array in the service having multiple instances would be bad because we would have multiple copies with different arrays in there now we have one of the same instance and we got it injected into post list and there we got our post service now all we need to do is call get posts let's do that and wire up the rest in the next lectures so time to reach out to our service and call get posts and for this i will not actually use the constructor though that would be possible but it's a better practice to use a special life cycle hook angular provides there are life cycle hooks which angular will automatically execute when it creates a component and one of them is the on init lifecycle hook we added by implementing an interface this is essentially a contract this class now signs it's called on init and it's imported from at angular core and this implementation now actually causes an error because now we're required to add a special method to our class here the ngon init method and once we add this everything is great again so now ngon init this is a function angular will automatically execute for us when it creates this component and it's recommended to do basic initialization tasks in ngon init and there i can now set this posts equal to this posts service remember this automatically created a property of the same name and there get posts like this now we fetch all the posts of course our posts are empty at the beginning though so we'll need to add posts and for this we can go to post create and there i also want to connect to my service so i'll add my constructor here too use the shortcut to automatically create a property named posts service and add to type post service import is added automatically by my ide don't forget these curly braces and now posts service is injected here too now here i want to reach out to the post service not an ng on init but whenever when i created a new post so here i will actually remove add output i don't need it anymore don't need the whole event emitter anymore remove both imports and instead instead of emitting i will now simply call this post service add post and pass my post there or we're actually expecting a title and a string and a content so i can also just pass these values here title and content as arguments i don't even need to construct the post in this file therefore so this means we can get rid of the post import here too so now we're calling add post from within the post create component we're calling get posts from within the post list component and in the post service we're connecting this let's give this a try if i enter something here and i click save post nothing happens and what's wrong here now what's wrong is that we're getting posts when the post list component is created with ngon in it and at this point of time we got an empty list there right it's an empty list of posts when we later add posts this doesn't do anything because we created a copy of posts and returned that so if we added the original array thereafter this doesn't well affect anything on our post list component by the way we can also remove input here so this is the reason why it's not working because we fetch the posts a copy of them before we edit them now there are a couple of ways of solving that we could not fetch a copy for example if we do that you will see that now if this reloads i get an error right because i should go to my app component html file and remove the bindings here we don't need that anymore to manage our posts let's also remove it in the typescript file of the app component and remove the post import so let's save all that so now if i go back it loads again and if i now enter something here you see the posts are added again but this is not the cleanest way of doing that i'm a fan of copying this to avoid unwanted manipulation of the posts in any component which is fetching our posts so a better way is to use an event-driven approach where we actively push the information about new posts being available to the components which are interested and for that we could use the event emitter but the event emitter is really meant to be used in conjunction with that at output decorator instead i'll use a feature provided by another package which is not part of angular but a core dependency the rxjs package you find here it's actually it's installed from the beginning rxjs is all about observables and this is a concept which can be a bit more complex to grasp it's essentially about objects that help us pass data around you could say and we'll dive deeper into observables step by step and i also dive deeper into them in my complete guide on angular here on udb and all the complete youtube series i got so we simply need to import something from that rxjs package to get started and that something is a subject now that essentially is an event emitter you could say but one which is actually for broader usage than the one angular ships with and now i will create this subject here as a private property too i'll name this posts updated again taking a property name here which sounds like an event this is not required but also not the worst idea and i'll create a new instance of my subject just as the event emitter this is a generic type and here i plan on passing a list of posts as a payload so we get the posts updated subject here and now when we have add post here or when we call this i don't just want to update my posts i also thereafter want to take my subject post updated and there it's not emit but next and this pushes a new value it emits a new value and this value is a copy of my posts after i updated them so this is now the subject we can still leave get posts in there even though it's not that useful right now but that could change later on what i now want to do is of course i want to be able to listen to that subject because it's emitting whenever we add a post how do i listen to it it's private so we can't directly access it to prevent other components from emitting data with it what i'll add is i'll add a new method here get post update listener the name is up to you of course and there i will return this posts updated and then there's a special method we can call as observable and now it returns an object to which we can listen but where we can't emit we can still emit from inside this file but not from files which received their reference with the help of this method so now we got get post update listener we can now go to the post list component again and i will still fetch that list of posts at the beginning even though it's guaranteed to be empty right now but what i will also do is i will set up a listener to that subject i do this by reaching out to this post service get post update listener this returns this observable and there we can call subscribe this is a method which is made available just putting this into a new line to make it easier to read it still is part of this statement here so subscribe now sets up a subscription and subscribe actually takes three arguments possible arguments the first one is a function which gets executed whenever new data is emitted the second argument will be called whenever an error is emitted this will never happen here and the third argument will be a function that is called whenever the observable is completed if whenever there are no more values to be expected this will also never be the case here because this is an infinitely living subject so to say we can always create new posts so we only add the first argument a function which is called whenever a new value is received and i'm using an arrow function here we receive some data here the posts right because in the post service we are emitting our new posts a copy of them so post is what we receive so i'll set the type to post array to be very clear about what we're getting here and in here i can then set this posts equal to the posts i just received to update them whenever this got a new value received a new value now one important thing this subscription here actually doesn't cancel whenever this component is teared down now right now this component never disappears because we got only one page we get no way of removing that component from the ui but later we will later there will be more components different pages and we want to ensure that whenever this component is not part of the dom the subscriptions which we set up in it are also not living anymore otherwise we create a memory leak so we will actually store that subscription in a new property which will be of type subscription so i'll import subscription from rxjs like this here subscription and now i will create a new property here private property maybe it doesn't matter posts sub which is of type subscription and it's undefined at the beginning and here in engion in it i will set this posts sub equal to this post service and the subscription we're defining here now we just need to unsubscribe whenever this component is destroyed and there is another live cycle look we can use for that we add it by implementing on destroy this forces us to add one hour method the ng on destroy method which is called whenever this component is about to get removed and there i will reach out to my posts sub not the service the sub and call unsubscribe and this will remove the subscription and prevent memory leaks and with this added if i go back we can try this add a post does this work and hit save post and you see we can add new posts here of course also with other content then the old one and now this is working with the service and whilst the setup is of course a bit more complex it saves us a lot of time since we don't have to build these chains of property and event binding and you already learned quite a bit about observables here with this event emitter we're using here so now let's move on in the last lectures we learned about this subject subscriptions and this seems to be related to something called observables time for a closer look so what's this observable thing as you could probably tell by the code we wrote it's all about us emitting data and listening to that data in different places of our application which makes it pretty helpful because we can well subscribe to certain updates changes and push these changes from a totally different place here's more theory on that so we typically think in observables and observers the observer is essentially the thing subscribing to an observable or the thing which establishes this subscription and manages it you could say there are three methods which are called on the observer's side and that's next error and complete now we called next on the subject in the last lectures and the subject is kind of the observable you could say but it's the observer who then does something upon the next call in that subscription callback we passed right that first argument we passed to subscribe that is the logic we want to execute whenever next is executed on the subject so to say so we invoke next through the observable or through the subject i'll come to the difference and the observer is what we basically pass into subscribe so it's a collection of functions that can do something upon these method calls and as i also explained briefly we cannot just emit next data so a new package of data so to say we could also have an observable where we want to throw an error maybe because we're doing some http calls behind the scenes that failed or we could also emit a complete event to basically say hey i'm done there are no more data packages to be emitted so no more next calls now a typical example but of course not limited to that is an observable that wraps a callback of an http request so we could wrap a normal xml http request an ajax request with an observable that basically takes that callback and whenever that request gives us back a response we instead use that observable to emit the response data or a possible error as a next or error message and that is essentially what we could do we could also complete the observable once the response is there because of course if the response is there this http request will not yield any other responses as i said it could also fail and that is how we could manage such a http request now in our app we didn't manage an http request though we managed a subject or our own event emitter therefore now a subject is really just a special kind of observable normal observable is kind of passive you wrap a callback or an event source like a click listener with it so you don't actively trigger when a new data package is emitted that happens when your http requests gets a response or when the user clicks something instead you just yeah well set up this listener and then you can subscribe to it a subject is more active we also subscribe to a subject but there we can manually call next and that makes it a perfect event emitter because we cannot just subscribe and wait for something which we can't directly influence instead we can directly influence when a new data package is emitted and that's exactly what we need in our application when we add a new post then we actively want to notify our entire application and that is what we can do with a subject so in general you can think of observables and therefore also subjects as streams of data or of values so we got one value and we can have more values which are emitted over time depending on the observable and the data source it covers then we have the observer so that's essentially this set of functions we can call next error and complete and for a normal value we typically would call next and if we have an observable that wraps something like a http request then it would do that for us and as i said we can have more than one value over the course of our application that depends on how we are using that observable eventually it may end but of course there are also observables that may never end for example if you're wrapping a normal click listener with it well then this will typically never end if you got an observable that ends well then the complete function here will be called and this is how it works this is how we work with observables how we should think about them if you want to learn way more about rxjs observables in the last lecture of this module you find a link to a in-depth series i created on youtube but that's the core mental model to wrap your head around for now we will mostly use the subject we will indirectly use some observables and i will explain what they do when we use them but in the end think of it as a stream of data which you can actively manage in the case of a subject or which is managed for you if you're wrapping some well source you can't directly influence and then you can decide what you want to do when new data is emitted in your subscription so now with this closer look at observables let's finish up our form here on the angular front and then do some first polishing before we move to the back end and add node so that we don't just have a front end but we also start working on the back end so here's our front end our angular app as we left it it's far from being finished and we will revisit it later in the course but for now let's do some polishing one polishing or one addition i want to do is would be nice to have some labels here right and actually you can add labels easily cue your forms in angular material by going to the html code and adding a placeholder attribute and there we could say title or maybe post title and we can also add that to the text area and say post content there and you will see that if you add such a placeholder you get it as a label here and you automatically got this floating label look here which is quite neat now one other thing i want to do is if i enter a new post here right now you can see the values stick around this forum doesn't get cleared and we can clear it in on add post where we get access to that forum by accessing form and then calling reset form like this if we now save that let's try this again let's enter something here let's click save post and you see this now resets the form and also the validity not just the values it doesn't just clear the form it also resets the validity which of course is exactly the behavior we want now that's almost all one other thing i want to add for now already is i want to add a action bar to the post whilst the functionality is missing right now we will add it later i want to be able to edit and delete such posts again the logic behind that and the code will be added later that means i want to have edit and a delete button here on this expand panel or on this expansion panel if we check the official docs we can see that there is a action bar or action row component we can nest into our expansion panel that looks pretty promising with that code copied if we go back to the post list component here we can add that below the paragraph in the expansion panel and we get a button here in the code snippet 2 and it will simply say edit i will actually add two buttons because i also want to have a delete button here you can also make this all caps to be closer to the original material style by the way where buttons tend to be all capitalized now the buttons if we add them like this can be seen let's quickly add a post here here are the buttons but they're not looking that spectacular to make them look a bit more spectacular what i will do is i will add some colors for the edit button i'll assign my primary color or maybe the accent color whichever one you prefer and the delete button here i will use my worn color because people should certainly be careful when clicking these buttons or this button specifically so now with that added if we add one more post we see edit and delete now since my accent color is this pink color it looks very much like the delete button so i will go for primary here to have a greater difference between the colors so let's add one more post here yeah that looks better and that is the last thing i wanted to prepare now again we will improve this code a lot later we will add a edit and delete functionality we will also add more components more pages on our front end but for now it's enough about angular let's move on to the back end let's move on to node and understand how that works and fits into our angular application you
Info
Channel: Academind
Views: 292,047
Rating: undefined out of 5
Keywords: angular, angular tutorial, node, node tutorial, mongodb, mongodb tutorial, express tutorial, mean stack, angular mean, mean tutorial, mean stack angular, mean stack tutorial
Id: 1tRLveSyNz8
Channel Id: undefined
Length: 155min 40sec (9340 seconds)
Published: Fri Jun 08 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.