Angular Components Beginner's Guide

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] components are like the LEGO pieces of an angular application if you don't know how to put them together properly you're not going to be able to build anything cool over the next 10 minutes or so I'll show you all of the basics and angular components and how to piece them together in an application this video is beginner level so if you know a little bit about JavaScript and web development you should be okay if you're new to the channel make sure to LIKE and subscribe and grab the full write-up from angular firebase com the first question we need to answer is what is a component in the first place and I think the most simple answer to this question is that it's just a controller for the user interface as a developer you write components to control how your app is experienced by end-users to show you this in practice I'm opening a brand new angular 6 app that was generated with the CLI then I'm generating a new component called home which you'll notice creates four different files in the app directory the vast majority of the logic that you'll write will be in the home component ES file the component itself is just a typescript class but it uses this component decorator to sprinkle in some angular magic the most important thing is that it allows us to bind data from this typescript file to the HTML template the first thing I want to show you is how to bind typescript code to your HTML let's define a property on this class called clicked that defaults to false now let's go into the HTML and let's imagine we have a button that we want to disable after it's been clicked we combined our typescript data to this attribute in HTML by wrapping it in square brackets disabled isn't something angular provides it's an actual attribute on the HTML element which I'm looking at here in the Mozilla documentation the special thing about angular is that we can wrap this attribute in square brackets and then bind it to our type script so instead of just passing it a boolean value like false we can actually pass it our clicked property which we can then toggle on our typescript as needed it's currently set to false so we should be able to serve our app and the button should be clickable which it is if we go into typescript and change our clicked property to true you'll see that the button is now disabled and unclick Abul in addition to attributes we can also bind to events that happen in the HTML so let's say we want to change this two disabled after it's been clicked once we can use parentheses to bind to the click event on this button and then we'll pass it a function that will define in our typescript to handle this event now we can switch back to typescript and define this event handler method we currently have the clicked property set to false but we want to set that to true once the button is clicked which we can do by calling this clicked equals true when we click the button this handle or will fire and in the button becomes disabled because it flips that property to true that's how you bind to events and attributes in angular but one other fundamental thing is interpolation and basically all that means is we're taking a raw value from our typescript and rendering it out in the HTML so for example let's say we have the title here that shows the angular version that we're currently running so the title is just a string value that gets created dynamically and then we can go into our HTML and use the handle bar syntax to interpolate it into the template if we reload the browser it should show us that we're running in angular 6 for this project so now that we have a working component how do we actually use it within the context of our angular application the most basic way is to declare it in the HTML with its selector which in this case is just app - home if we go into this project's app component we can just declare our app home page there and it will be rendered out like it's just a regular HTML element but we can also load it with the router and have it appear where this router outlet is based on a certain URL path check out episode 113 to learn all about the router but the most basic use case is that we setup a path and then we point this path to our component if we reload the app in the browser you'll see it looks exactly the same but if we open the augury plug-in and go to the router tree you can see that it's being loaded by the router instead of just the HTML directly you can also load components dynamically but without changing the route a common use case would be like a pop-up or a modal window this technique is used frequently in the ionic framework for example the alerts controller will dynamically load an entry component whenever the button is clicked and lastly the cool new way to load a component is with angular elements which allows you to convert it to a regular web component and then use it outside of angular completely so you could just drop it into a regular HT mell page which you can learn all about an episode 102 the next thing we're going to look at our directives and a directive is basically just like a component but without its own HTML or CSS instead it attaches to a host element and changes the behavior of it to demonstrate this I've added an object called boat with some dummy data to our component then perhaps the most useful built in directive and angular is ng-if and any directive that starts with a star means it's a structural directive and controls how elements are rendered in the Dom in this case we're attaching an NG F to a div and it will only render this div if the right-hand side resolves to true so going back to our clicks property we're only going to show this boat data if the button has been clicked when we open the app you can see that it looks just like it did before but when we click the button it displays our boat data you'll end up using ng F all the time and angular and there's one other directive that you'll use very frequently as well which is ng 4 you can use it to loop over an array of data so let's imagine we have an array with multiple boats in it we've already mapped out how we want each boat to be displayed but instead of using ng if here we can replace it with ng 4 then we'll iterate over the boats array by saying let boat of boats then the div that this directive is attached to will be rendered for each item in that array if we open the app you can see we now have multiple boats utilizing the same presentation logic so those are super powerful but another thing you often want to do is display different CSS classes conditionally based on some logic in your type script just as a basic example let's imagine we have a green and red CSS class we can use the ng class directive to control which CSS class gets applied to the h1 title based on the name of the boat so we'll pass the directive and object where the left-hand side of each object property is the CSS class we want to apply then the value or the right side is an expression that resolves to true or false which in this case will either be boat name equals Starfire or boat name equals Oracle now we get a different color for each title based on this logic so far we've only looked at built in directives in angular but you can also build your own custom directives let's go ahead and build our own with the angular CLI by running an ng generate directive which we'll call magnifier that will increase the size of an image when it's hovered over overall this looks pretty similar to a component but the key difference is that there is no HTML template or CSS styles instead it's used as an attribute on an HTML element this particular directive will be used to modify the width of an image element so we can bind to the host elements width by using the host binding decorator then any image that uses this directive will start with a width of 200 then we also want to listen to the mouse enter event to know when the user is hovered over the image with their mouse with that we can use the host listener decorator pass in the Dom event that we want to listen to and then define a function to handle this event in this case what we want to do is really simple just increase the width from 200 to 300 now we'll switch back to the HTML in our component and we currently have an image in there that displays the boat image with a width of 200 let's go ahead and take this out and replace it with the app magnifier directive if we go back to our app and hover over the images you'll see that they're resized as soon as we hover over them not the most useful thing in the world but you get the idea of how you can use components and directives together to write really dry reusable code there's another mechanism in angular that helps us write reusable code called pipes a pipe is always used in an interpolated value in the HTML so let's imagine we have a big number here we can use the built in number pipe to round this down to 3 decimals angular has some useful built in pipes but the real power comes when you start building your own custom pipes and chances are somebody's already written the code that you need for your use case so make sure to check out the angular pipes of github repo for a full list of examples there's one really special pipe that I want to talk about now which is the async pipe in web application you're commonly fetching data asynchronously as a promise or an observable and the async pipe allows you to do this automatically in a predictable way directly in the HTML in this example I'm converting our boats array into an observable by using the rxjs of method so now it becomes an observable object so our regular ng for loop isn't going to work what we can do is simply add the async pipe to our for loop and now it's going to convert that observable to an array by subscribing to it and in addition it also unsubscribes when this component is destroyed that's a whole nother subject on rxjs but just know that it's a very useful mechanism for simplifying your angular code in a real app we'd probably be fetching these boats asynchronously from a database and the async pipe allows us to treat them more like a synchronous plain JavaScript array at its core a pipe is very simple it's just a function that takes in a value and then spits out another value each of our boats has a year property on it let's say we want to only display the last two digits in that four-digit year all we have to do is go into our custom pipe and then implement this transform method the value represents whatever value is inside the handlebar syntax in your HTML then the value you return is what you want to be shown in the HTML in this case we'll convert the number to a string and then grab the last two elements on that string then we can go add it to the boat year and our HTML and then if we reopen the app we'll see that we only get the last two numbers on the year so now that you know a lot about components pipes and directives I want to talk about a concept that's really important for angular developers and that's never touched the Dom if you're an experienced JavaScript developer you're probably used to doing something like this where you call document query selector then grab some element in the Dom and change its inner HTML and when you're building a progressive web app this code will work perfectly fine because the Dom exists in a web app but if you write code like this and you ever want to do server-side rendering or build a native mobile app this code will not work because the Dom does not exist on other platforms so now you know why the use of libraries like jQuery are generally discouraged in angular now let's switch gears into the component lifecycle a component is just a class so the very first thing that happen in its lifecycle is the constructor aspired but components have relationships with other components and they have bindings that are initialized in the HTML so things get a little bit more complex in angular you typically don't do anything in the constructor except add your dependencies and that's because your property bindings aren't guaranteed to be available until you run ng on it knit which is the first time change detection runs in this component so the uninit lifecycle hook is where you do all of your setup maybe you're fetching from an API or you're setting up a reactive form or something along those lines I'll go ahead and add our boats observable to energy on an it just to simulate it coming from a database or API the very last thing to happen to a component is that it's destroyed which triggers the on destroyed lifecycle hook this is where you do any teardown for your component and angular that is commonly unsubscribing from an observable to prevent things like memory leaks and performance issues on an it is by far the most common hook that you'll use but if you have child views inside of your component you might also want to use after view in it which will ensure that your child views are loaded as well now that segues into a really important concept in angular which is change detection behind the scenes angular is using something called zone j s that will listen for any events or asynchronous activity in your app and then re render components as needed you can determine when change detection is happening by using this do check lifecycle hook you wouldn't normally use this to do anything significant but it is useful for debugging at times if you're building an interactive app this lifecycle hook will be triggered constantly you can see we get the first console log when the component is initialized that's when the ng on an it lifecycle hook runs and then as we hover around different events take place and that triggers change detection and the console log in the browser so now I want to segue into a concept that is also common in other JavaScript frameworks like react in view and that smart components versus dumb components or also commonly called stateful versus stateless or container versus presentational and basically all this boils down to is a separation of concerns to make your code predictable a smart component is generally a page or container that controls how things work throughout the app well the dumb component is only concerned with presentation logic I have generated a new component called boat that will be our dumb component it's going to take the data from this ng for loop and extract it into its own isolated presentational component this allows the parent component to focus on more low-level things like synchronizing the state of the app and fetching the items from the database as your app grows in complexity this just becomes an easier way to rationalize what's happening in so the home component is a container that fetches the data while the boat component is only concerned with presenting the data in the UI there's a ton of other things we can talk about with angular components but many of those you'll see in practice as we build out different features on this channel I'm gonna go ahead and wrap things up there if this video helped you please like and subscribe and if you want to build more advanced real world features consider becoming a pro member at angular firebase comm you'll get exclusive pro videos every week plus a copy of the angular firebase Survival Guide thanks for watching and I'll talk to you soon
Info
Channel: Fireship
Views: 95,135
Rating: 4.9510269 out of 5
Keywords: angular, angular 2, webdev, app development, typescript, javascript, lesson, tutorial, angular 6, angular components, angular directives, angular pipes, component tutorial, component architecture, angular basics, angular beginners
Id: 23o0evRtrFI
Channel Id: undefined
Length: 13min 52sec (832 seconds)
Published: Wed Jun 20 2018
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.