Angular for Beginners - Let's build a Tic-Tac-Toe PWA

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
welcome to my first ever angular tutorial for beginners if you've learned a little bit about JavaScript HTML and CSS the next step is to make the world a better place by building an app that people can use today we'll build a tic-tac-toe game from scratch deploy it and make it installable on desktop and mobile applications as a PWM and despite angular's reputation as an enterprise-grade framework you might be very surprised at how easy it is to start being productive with angular even as a beginner and you'll especially love it when you start building complex products in real life if you're new here like and subscribe and if you want to get really deep into angular check out my new angular course on fire ship IO first of all what is angular because the word angular refers to so many different things it's a declarative UI framework a code bundler a tool for building progressive web apps it handles server-side rendering provides libraries for forms testing animation and so much more and it's all wrapped up in a highly performant package that will help reduce decision fatigue web developers especially have a huge number of open-source libraries to choose from when building a product and the status quo is always changing wait a minute angular ships with a ton of features out of the box many of which anticipate the complexity that you'll face as your app grows but almost all of its features are optional and can be adopted as needed so what does angular really do at its core then the short answer is that it helps you build complex cross-platform applications using web technology like JavaScript HTML and CSS but I think the best way to answer that question is to just show you by building something from scratch so over the next 15 minutes or so we'll build a tic-tac-toe game we'll add a design system to it we'll make it a progressive web app we'll deploy it and finally install it on our local system as if it were a native desktop or mobile app that might sound like a lot to do in 15 minutes but don't worry we have a superpower known as the angular command-line interface and this is not your typical CLI this thing is really powerful because of angular's conventions we can generate a lot of code automatically at this point I'm assuming you have no js' installed on your system and will run npm install global at angular CLI this will give you access to the ng command in your terminal and the first thing we'll want to do is generate a new angular app we can do that by running ng new with the name of the app and it will ask us if we want to add routing we'll go ahead and say yes and we'll choose SCSS for our styles and then we'll go ahead and open up our app in vs code there's a couple of extensions you'll want to have first is the angular language service which will give you syntax highlighting in your HTML templates and then I'm also installing the angular console which is a tool that allows us to simply point and click on CLI commands as opposed to typing them out manually in the terminal go ahead and find the serve command then hit run what happens is that our code is now bundled with web pack using live reload so every time we make a change to our code it will be reflected in the browser and you can see that on localhost 4200 now if you're new to web development you may have not experienced this yet but one of the most painful aspects of the job it can be bundling your code when building a web application you need to target multiple browsers and on top of that you want to keep the JavaScript bundle size as small as possible doing this from scratch in a complex application is a major pain but not with angular click the build command and see what happens angular will automatically minify and bundle your code and will also generate multiple bundles for a differential loading this means the browser will always load the smallest javascript bundle possible based on the features available in that browser and we can see all that raw JavaScript code by going into the dist folder and this is the folder that we would actually deploy to a production hosting account or server now let's take a look at some of the files in this initial application we have a few TS config files here which were automatically generated and set up for this project angular was really the first major framework to encourage the use of typescript and you now see it is almost a standard on large complex projects [Music] now the default angular app also comes with testing using karma and Jasmine but there are other schematics or other extensions for the CLI you can use for other testing frameworks like jest and cypress and that's just another thing that angular does out-of-the-box it sets up your testing utilities so you don't have to think about configuring them but what good is any of this if the framework doesn't actually help us build a front-end UI because angular at its core is very similar to other UI frameworks like react spelt and view just to name a few you'll find these same concepts in angular that you find in these frameworks component based UI architecture where you can pass properties or data from one component to another the place where we write our actual UI code is in the source app directory by default angular generates an app component which is essentially the entry point into the app we can see how this works by opening up the index.html file which is just plain HTML the special thing is that we have this app root element in the body this element will be replaced with our actual angular JavaScript application and that initial parsing of the JavaScript is called bootstrapping but the main thing you'll be doing in angular is creating a UI by building and composing components together and there are three main pieces to any component the component typescript is where you define your custom javascript logic and also define the internal state of the component then you have your HTML which contains the actual visual UI and allows you to bind data from the typescript to that template and lastly you have a style sheet which is scoped to that component meaning these Styles won't bleed out to other components let's go into the app component HTML first and delete all of the boilerplate code in there leaving only the router outlet angular provides a very powerful router out of the box which allows you to map components to URLs in the browser and the router can even help you do something called code splitting with web pack to lazy load certain parts of your JavaScript bundle we're not going to cover it in this video but just know that it's a relatively complex thing that angular makes trivial now from this point I want to build something meaningful so let's build a little game of tic-tac-toe the idea itself is inspired by the react to toriel and it provides a good baseline for understanding the mechanics of the framework we'll start by building a bare-bones game then we'll add a design system and lastly we will deploy it as a PWA so the first thing we'll do is generate a component to represent an individual square will find the generate command with the angular console will generate a component and give it a name up Square and a lot of times in angular you might not need to have your component separated into three different files so when running this command from the angular console we'll actually select the options for inline template and inline styles you'll see this created a square directory along with a square component inside if we open up the component you'll see that we're importing a component and on an it from angular core on an it is what's known as a lifecycle hook which allows you to run some code when the component is first initialized it's not required for this component so I'm going to go ahead and delete the references to it and what we're left with here is just a plain angular component every component starts with a component decorator and decorators are these things that start with an @ symbol and you can watch my full video on typescript decorators if you're curious to learn how they work but in the case of angular they allow us to pass in an object that configures the way this component behaves first you'll notice the selector option this is the name of the component as it will be declared or used in the HTML let's go ahead and open the app component to see how that works if we start typing Apps Square it should autocomplete in vs code and then we can hit tab to complete it and then if we're still serving the app we should see the content of that component in the web page the next thing you'll notice is the template angular provides a special templating language that empowers your HTML with JavaScript like logic you can use conditional expressions loops and bind data directly to the HTML to write templates that are expressive and easy to understand and also highly performant when it comes to reacting to data changes within the app and that's why declarative UI frameworks like react angular etc are so popular they make it easy for you as a developer to keep your app data in sync with the actual UI how it appears visually for the end user in angular we can bind data to a template by simply adding it as a property to the component class just to demonstrate this I'll add a random number and then I can interpolate it in the template by using double braces and now we should see the random number in the screen under the hood angular is doing a thing called change detection where it's looking for changes to these properties and then updating the UI in a highly performant way and all we have to do from a development perspective is change the value of the property for example if we set up an interval here and change the random number to a different random number you'll see it's updated in the screen every 500 milliseconds so when you set a property on a component class that's like setting its internal state but in many cases you want to pass in the property from a parent component and that's exactly what we want for this square we can allow properties to be input into this component by using the input decorator if we start typing input and then tab it will automatically import this decorator for us and then we can set the property name to value and we could even use typescript here to limit this value to a certain subset of string values or some other type if we wanted to and now we can go back up to our component declaration in the app component and now we can input this value from the parent component which can be just a string value or if we're at value in brackets it will take an actual expression or a dynamic value from this parent component and that means you can pass a complex object from parent to child now if we look at our square component it only has a single input there is nothing in this component that allows it to modify its own state it all comes from the parent so we generally call this a UI component or a dump component dump components are a good thing they're easy to test and they're only concerned about the UI so there's not much to worry about in terms of bugs and things like that but in order to build a tic-tac-toe game we'll need some kind of smart component to manage the state or the data between the various squares let's go ahead and generate that component will call it board and just stick with the default options now our board component will be our smart component meaning it has internal state they can change we have the squares property which represents the nine moves on the game board which will be an array of strings and then we have a property called X's next which is a boolean to help us determine the current player and then we have the winner which will either be X or O now every component has a constructor and also lifecycle hooks the constructor runs immediately when this class is created but you don't generally do anything in the constructor aside from inject your dependencies which we'll look at in a future video if you have initial setup work that needs to be done in a component you'll use the ng on a net life cycle hook in most cases in our case we'll write a method on this component called new game and its responsibility is to set up the initial values when starting a brand new game for our squares property we'll create an array with nine elements in it and then we'll fill them with null values initially when a user clicks on a square these values will be spliced with either an X or an O we'll set the winner to null and X is next to true now when working with data on a component you may want to compute a property based on one of the main pieces of data that changes in our case X is next determines which player is currently using the game board that's a boolean value but we'd also like to show the name of the player as a string which would be X or O so we can create a computed property by using a type script getter we'll go ahead and call this property player and if X is next is true then the next player will be X otherwise it will be o now anytime the X is next value changes this computed property will be changed and reflected in the UI as well now the next thing we'll do in this component is define a method which will serve as an event handler for when the user clicks on one of the buttons to make a move when that click event happens we'll check the index in the array that they clicked on if that Square has already been clicked then we won't do anything but if it's empty or null and we'll splice in the index of the square that user clicked on with the current player that we've computed in this component and then we'll also toggle the X's next boolean to its opposite value by using an exclamation mark in the last thing I'll do is write a method called calculate winner this code mostly comes from the react to toriel and it's basically just an algorithm that determines if the user has won the tic-tac-toe game I'm not going to spend time explaining the exact implementation details but feel free to copy the source code from the github link in the video description so now let's head into the HTML template to see how we can bind the data properties we define on the component class to our actual UI we'll want to show the name of the current player show the winner if the exist and then also loop over the array of squares so the user has something to click on the player property that we defined what they get her behaves just like any other property we can simply use it with the handle bar syntax to interpolate it in the template now the other thing that you'll commonly do in a web application is handle events and an angular we can bind to events by using parentheses and you'll notice that when we do that angular's tooling will automatically give us a list of all the possible events to add here and then we bind a handler to this event which vs code will also autocomplete so in angular you get amazing tooling both in the typescript and also in your templates now for this tic-tac-toe game if we have a winner we want to display a conditional template only when that winner exists and we can make that happen with what's called a structural directive if you type in star you'll see the different structural directives at your disposal but the most common one is ngf and it allows you to only render the HTML that it's bound to if the value on the right side evaluates to true or it can be coerced to a truth eval you to be more precise and so when the winner is present then this h2 element will be rendered in the Dom now the final step is to put together the actual squares that represent the game board another common structural directive and angular is ng4 so first we'll declare our app square component then we'll add ng4 to render this component multiple times based on the array of squares inside of ng4 we say let vowel which creates a template variable named vowel that we can now use in this template and if we also want access to the index we can set a template variable of I equal to the index and now we can put these variables to use the first thing we want to do is pass the value down to the child app square component and it can use that value to render an X or an O in the button and we'll also bind to the click event to make a move on that index when the user clicks on the square now that takes care of our template logic but there's one thing that's missing and that is our CSS styling to give us a 3x3 grid CSS grid makes this very easy we just set up our main element to display grid and then we'll display the columns at 200 pixels each at this point you can serve the application and you should now be able to play a game of tic-tac-toe but we have one major problem at this point the app looks horrible so what we'd like to do is add some global styling like a design system to give us a consistent UI that looks great but usually setting up something like that is pretty involved but fortunately the angular ecosystem has a variety of third-party component libraries that we can easily add to this project with a single command and that means our app can look great right out of the gate without any decision making or configuration on our part there are plenty of great options to choose from like angular material ionic and others but today we're going to go with nebula not only do the default components look great but they also just released a new feature called UI bakery and it's a tool that allows you to visually create components and then download angular code expect a video on this topic in the near future for right now we'll go ahead and add nebula to this project by using the ng add command if we run ng ad at nebula theme it will automatically install and configure nebula in our project I'm gonna go ahead and choose the cosmic theme because that sounds cool and we'll also say yes to customization and animation you'll notice a few key changes to the project we now have a themes s CSS file which we can use to customize the variables used in the theme and then we can go into the app module and we'll see that we have a few ng module is imported here we're not going to talk about ng modules in this video but they are discussed in detail in the full course basically they're just a mechanism that makes it possible to use angular in a progressive way or in other words only use the parts of the framework that you actually need in our case we'll go ahead and import the nebular button module because that's the only nebula component that we want to use so we don't have to package the entire thing which would increase our bundle size and decrease performance and also if we go into the app component you'll see that we now have a bunch of components that are prefixed by NB for nebula and already the UI is looking a lot more interesting but one obvious way we can improve this is to change the styling of an individual square based on its state if we go back into our square component we now have access to the NB button directive with this directive you can apply the nebular button theme and behaviors to any HTML element using the directive as is we'll give you the default nebular button which we'll go ahead and do when the value is null or when the square has not been selected then we'll go ahead and set up a couple of additional buttons as well and these buttons will take additional properties on the NB button directive and the design system provides a lot of different ways to customize the button right out-of-the-box for example we'll use this hero button which gives it a nice little gradient but check out the component library and the docs for a full set of examples then we'll conditionally render each button depending on whether or not the value is X or O using the ngf directive now I realize I'm going through this code very fast but again make sure to reference the link to github in the video description to find the full project source code and one last thing I'll do is also go into the board component and for the start new game button we'll go ahead and display an outline button there and with just a few minor changes we now have a much better looking game of tic-tac-toe so this kind of highlights my favorite thing about angular and that is getting things done quickly the tooling truly is amazing and there's a lot less configuration required to get to something meaningful but there's still one more thing I promised you and that's to make this a progressive web app that can be installed as a native app and believe it or not that's actually the easiest part of this entire video let's head over to the angular console click on add and then you'll see a full list of the different schematics that are available to you the one we're interested in is at angular /pwa when you run this command it does several important things related to pwace the first thing it does is add the JavaScript code needed to load a serviceworker in the angular app and then it gives you a configuration file that you can use to customize the behavior of the serviceworker and the worker is there primarily to make your app work offline so you can customize the behavior of how those pages are cached and stored offline and then you'll also notice that it adds a manifest file and some icons for the actual install button for the app now in order to determine if we have a valid progressive web app we need to run this app in a production environment so the first step in that process is to run ng build which we can do with the angular console and that will compile all of our typescript code down to JavaScript in the dist folder there's just one thing missing and that's an actual place to deploy our code my personal favourite place is firebase and we can easily add firebase to an angular project by running ng add at angular fire this is going to ask you for a firebase project so you'll need to have signed up for a firebase account if you don't have one already and firebase hosting can be used on the free tier by the way the only thing left to do at this point is run ng deploy that's going to automatically deploy our production app to the firebase hosting account that will give you the hosting URL when it's finished and now we can play tic-tac-toe on the web but here's the coolest thing about this if we go to the audits tab in chrome dev tools we can analyze our app as a PWA and you can see we hit the green check marks on everything and what this means for the end user is that the app is now installable on their device and pwace are supported pretty much everywhere now in fact we can even install it on Windows desktop by hitting the install button in chrome it will add a shortcut to the desktop and it will open up the app in an actual Windows window and now people can use your web app as if it were a traditional desktop app and the same goes for mobile apps as well so I'll just finish up by saying that angular is a really awesome tool when you know how to use it and if you want to go beyond the basics and learn how to build a real world progressive web app consider becoming a pro member at fire ship IO you'll get access to the brand new angular 8 course and a whole bunch of other Pro content thanks for watching and I will talk to you soon [Music]
Info
Channel: Fireship
Views: 253,206
Rating: 4.8924704 out of 5
Keywords: webdev, app development, lesson, tutorial, beginners, beginner, basic, angular tutorial, angular basics, angular for beginners, angular 8, angular components, learn angular
Id: G0bBLvWXBvc
Channel Id: undefined
Length: 20min 45sec (1245 seconds)
Published: Mon Sep 16 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.