Angular is a TypeScript-based free and open-source web application framework created by Google.
We just published a 2-hour Angular crash course on the freeCodeCamp.org YouTube channel.
Slobodan Gajic created this course. Slobodan has created a bunch of amazing courses on his own channel.
In this course you will learn how to use all the main parts of Angular using TypeScript. By the end, you will be ready to build your own projects using Angular.
Here are the sections covered in this course:
- Lifecycle hooks
- Text interpolation
- Components Communication
- Component Styles
- Template Statements
- Property Binding
- Attribute, Class & Style
- Event Binding
- Two-way Binding
- Attribute directives
- Structural directives
- Dependency Injection
- Template-Driven Form
- Reactive Forms
- Form Validation
- HTTP Client
Watch the full course below or on the freeCodeCamp.org YouTube channel (2-hour watch).
This is an amazing beginner's Angular course, Slobodan is a very experienced developer.
And he teaches the basics of Angular, using diagrams, animations, and of course code.
Today, I'm starting with a new video series about Angular framework.
And in this series, you will learn all the things you need to master Angular framework.
I'll start with basic stuff like components and pipes, and slowly progress, the most complex features of this framework.
So let's start.
In this section, I'm going to explain what Angular is give some brief overview of its features and explain why you should use it.
But before we start, make sure to check my channel for more videos, and tutorials about front end development.
Now, let's start.
Angular is opinionated UI framework for building mobile and desktop applications.
And it's built using TypeScript by Google.
You've probably heard about that one.
Also, it is an open source and helps us build dynamic and single page applications.
It is completely based on components.
It consists of several components, which forms a tree structure with parent and child components.
Angles versions beyond two plus are generally known is angular only.
The very first version of Angular is known as Angular JS.
So why Angular? Well, because it's supported on various platforms, web, mobile, desktop native, it's powerful, modern, has nice ecosystem.
And it's just cool that the mist, let me give you some facts.
Angular presents you not only the tools, but also design patterns to build your project in a maintainable way.
In an Angular application is crafted properly, you don't end up with a tangle of classes and methods that are hard to modify, and even harder to test.
The code is structured conveniently, and you won't need to spend much time in order to understand what is going on.
Angular is built with TypeScript, which in turn relies on GS ESX.
You don't need to learn a totally new language, but you still receive features like static typing, interfaces, classes, namespaces, decorators, etc.
No need to reinvent the bicycle.
with Angular, you already have lots of tools to start crafting application.
You have directives to give HTML elements dynamic behavior, you can power up the forms using form control and introduce various validation rules.
You may easily send a synchronous HTTP requests various types, you can set up routing with little hassle, and there are many more goodies that Angular can offer us.
components are decoupled, angular strive to remove the tight coupling between various components of the application.
injection happens no j style, and you may replace various component VDS.
All DOM manipulation happens, where it should happen.
with Angular euren, tightly coupled presentation and application logic, making your markup much cleaner and simpler.
Testing is at the heart.
Angular is meant to be thoroughly tested, and it supports both unit and end to end testing.
Angular is mobile and desktop ready, meaning you have one framework for multiple platforms.
Angular is actively maintained, and has a large community and ecosystem.
You can find lots of materials on this framework, as well as many useful third party tools.
The architecture diagram indentifies, the eight main building blocks of an Angular application.
Angular apps are modular, and an Angular has its own modularity system, called Angular modules, or enshi.
Every Angular app has at least one Angular module class, the root module, conveniently named app module.
While the root module may be the only module in a small application, most apps have many more feature modules.
Each a cohesive block of code dedicated to an application domain, or workflow are closely related set of capabilities.
in Angular module, whether a route or a feature is a class with an NGO module decorator.
Angular templates are dynamic.
When Angular renders them it transforms the DOM according to the instructions given by directives.
Metadata tells Angular how to process a class.
Service is a broad category encompassing any value function or feature that your application needs.
Almost anything can be a service.
A service is typically a class with a narrow, well defined purpose.
It should do something specific and do it well.
Examples include logging Service data service message bus tax calculator application configuration.
There is nothing specifically about Angular services.
Angular has no definition of a service.
There is no service base class and no place to register a service.
Yet, services are fundamental to any Angular application.
components are big consumers of services.
Now let's talk more about components in detail.
components are the main building block of Angular application.
Each component consists of an HTML template that declares what renders on the page, a TypeScript class that defines behavior, the CSS selector that defines how the component is used in our template, and optionally, CSS styles applied to the component.
A component must belong to an NGO module in order for it to be available to another component.
Why do we use components? There are many reasons but the main ones are, you're able to reuse our code so we don't duplicate simplify component based architecture, easy to do error handling, and breaking down the complexity into smaller pieces.
prerequisites for these sections are install the angular COI, and create an Angular workspace with the initial application.
If you don't have a project, you can create one using mg new project name, where project name is the name of your application.
Although the angular satellite is the easiest way to create an Angular component, In this tutorial, we will create our component manually.
To create a new component.
Navigate to your Angular project directory.
Create a new file hello world component Ts file.
At the top of the file, add the following import statement.
After the import statement, add a component decorator decorator marks a class is an Angular component in provides metadata that decides how the component is use at runtime.
Choose CSS selector for the component.
This is a tag which you will be using in your template files to render your component defined the HTML template that the component uses to display information.
In most cases, this template is a separate HTML file, but I'll use it within this file.
To define a template as external file.
Add a template URL property to the component decorator.
For a template within the same file, use template property.
Select the styles for the components template.
In most cases, you will define the styles for a components template in a separate file.
Again, I will use it within the file to declare the styles for a component in a separate pile, or the style URLs property to the Add Component decorator.
But for the styles within the component, add styles property, add a class statement that includes the code for the component.
Here we can define properties, methods, catch component lifecycle events, and do dependency injection.
But I'll talk more about these in the next video.
Now, all the public properties that are defined in the class are accessible in the HTML template.
And this is one of the most powerful things here, I'll create a title property, and I will include it in the HTML.
import that new file in the module where you want to use it, to make it available for the whole app imported in the root module.
In order to see our component, we can use our CSS selector inside of our app component or any other component.
And this is your first component.
Very simple though, you can reuse across your area.
In this section, we are talking about lifecycle hooks.
There are special functionality in Angular that allows us to hook into and run code.
And a specific lifecycle event of a component or director can look at them as pages of component life.
Like every living being cast, they get born, they change, they grow, and eventually they die.
With lifecycle hooks, you can gain better control of our application when we want to use them.
For example, if you want to fetch some data in this page in your component, you will do that inside of MG on in its lifecycle when a component gets initialized, or if you need to clean up your component remove some subscriptions, you might have to prevent memory leaks, you will do that inside of NGO ondestroy lifecycle just before component gets destroyed.
This is the list of all hooks in exact order how they get initialized, but most use ones are on it on changes and ondestroy.
let's implement the NGO on it, hook it up.
We'll be using this hook the most first in input on an interface from Angular core.
Next, we want to implement this interface inside of our class.
To implement any hook, you just need to add an energy to the interface name, and you will get the method needed for implementation.
So in this case, it's mg on in it, we will create a simple function for logging some values to the console.
Now, I will create a property they will save that function so that we can clean it up at the end.
In the NGO on init method, let's create a simple set interval method which will make a console log on every second.
If you leave our component like this, when the component gets destroyed, our interval method will continue to log to console.
To fix this side effect, we need to use the NGO on destroy hook.
Import on destroy interface in place the next on in it.
Now create the NGO ondestroy method and in this method, you need to clean up this interval.
Simply use a clear interval method with our property passed as an argument.
And now our component has been cleaned up.
Using lifecycle hooks, we're going to fine tune the behavior of our components during creation, update and destruction.
Next, text interpolation.
Text interpolation in Angular is a one way data binding technique that is used to transfer data from a TypeScript code to an HTML template.
It uses the template expression in double curly braces, also known as a mustache syntax to display the data from the component to the view.
When do we need a text interpolation? Every time we want to make something dynamic in our HTML template.
To illustrate how interpolation works, let's create a new variable in our Ts class.
You can use interpolation to display the value of this variable in the corresponding component template.
Angular replaces title with the string value of the corresponding component property.
In this case, the values hello world.
Now let's talk about template expressions.
A template expression produces a value and appears within double curly braces.
Let me show you an example.
Angular resolves the expression and assigns it to a property of a binding target.
Also operators such as new type of or ease to solve.
You can't use chaining expressions decrement, or increment operators and some of the ies 2015 plus operators.
expressions can also invoke methods.
So let's create one name of our method that will be get made.
And in this method, we are returning value for displaying it in our template.
In this case, it will be a minimum value.
Couple of things I want to mention, you should keep application logic in the component as much as possible, where it is easier to develop and test.
Also, expressions should finish quickly to keep the user experience as efficient as possible, especially on slower devices.
And template expression should not change any application state other than the value of the target property.
Reading a component value should not change some other displayed values.
Now let's learn how to communicate between the components.
in Angular application usually consists of many separate components.
And in order to make them work together, we need communication between them.
You can think of components as family members.
And if communication between the parents and kids is fluid and efficient, your home will be a happy place.
There are four ways to communicate between the angular components binding using input and output reference by using view child and content provider using services and templates outlined.
In this tutorial, I'm going to cover the first two ways as we haven't covered services yet.
And a template out that is a little bit of that.
First use case is when we want to send data from parent to child using input decorator.
Input decorator takes the value passed from parent and stores that value in the child property.
Let me create two components using Angular CLA.
I will run the following commands and G generate component parent and angiogenic component child.
In our child component, I will import input decorator.
In name our input is child message of type string In a template of the same component, I will display this property which is going to be passed from a parent.
Now, inside of our parent component in the template, we want to place our child component and to pass the value to the input property we just created.
The name of the property is the one we defined in the child component, and the value is going to be a Hello message.
Next, we want to place our parent component inside of our root component.
And if we preview it, we can see their message from parent has been displayed in our child component.
Second use case is when we want to send data from child to parent using output decorator.
Output decorator marks a property in a child component is a doorway through which data can travel from the child to the parent.
This approach is ideal when you want to share data this occurs on things like button quick form entries in other user events.
To raise it an event, an output must have the type of event emitter, which is a class in the angular core that used to emit custom events.
In the child component input output decorator an event emitter.
We declare a message event variable with the output decorator and set it to equal to a new event emitter.
And then we create a function named send message that calls a method on this event with the message we want to send.
Lastly, we create a button to trigger this function.
In the parent, I will create a function to receive the message and I will just simply alert this message for demonstration purposes.
Now in the parent template, call our function once the event from the child component occurs.
And the name of that event is the one that we defined with output decorator.
Very simple and effective.
Compared with all other approaches for communication, binding is the cleanest and the simplest one, it is the most maintainable wait for passing data, as binding is always the most preferable way that Angular developers should consider first.
Third use case is when we want to send data from child to parent using view child view child allows the child component to be injected into a parent component.
It will give the parent access to its properties and functions.
Each child won't be available to give access until the viewer has been initialized.
This means we need to implement the after view init lifecycle hook to receive the data from the child.
First create a message property in our child component.
Import view child in after view init.
From Angular core in our child component.
For our view, child decorator, pass our child component as an argument in named as child.
Next, implement after view init lifecycle hook.
By the way to learn more about Angular hooks, check the part two of this video series inside the MG after view init method just alert the message property of our child so that you can see that we have access to it.
And if we start our application, you can see that we are displaying a message from the child component.
Next, we are discussing component styles.
Being able to style your app is very important because it allows you to make your app unique and attractive.
In a way it's like a beauty salon.
World Without CSS would be an ugly place.
css gives us the opportunity to play with a page layout, adjust colors and fonts, add effects images, and so on how to add styles to Angular components.
There are three ways you can apply style by setting style or style URLs metadata, in light the template HTML, and three with CSS imports.
I created one blank component with only h2 tag in the view to demonstrate all different ways we can style it.
You can add a styles array property to the component decorator, each string in the array define some CSS for This component can load styles from external CSS files by adding a styles URL property to a components decorator.
And now styles from external file are being applied.
Next, you can embed CSS styles directly into the HTML template by putting them inside of style tags.
You can also write the link tags into the components HTML template.
One note here is to be sure to include the link styles file among the assets to be copied to the server when building.
You can also import CSS files into the CSS files using the standard CSS import rule.
I usually use this approach to import variables.
Reminder, these styles apply only to this component.
So if you held h1 tag in a child or parent component, it won't be applied there.
By default view encapsulation is said to emulated and emulates the behavior of the Shadow DOM by pre processing and renaming CSS code to effectively scope the CSS to the components view.
We can remove these additional CSS selectors by setting encapsulation to none.
And now our styles are being applied globally.
Global styles are by default defined in the style CSS file, and you can find more global styles in the angular JSON file.
Another thing is that if you're building with the COI, you can write style files in sass, less or stylus, and specify those files in the component style URLs metadata, be the appropriate extension as in the following example.
Now let's talk about special selectors.
Use the host pseudo class selector to target styles in the element that hosts the component is opposite to target elements inside the components template.
For example, we can write the following code.
We can style host styles with the given selector by using the function form as the following.
And if you add active class to host component, you can see that styles are being applied.
Now let's talk about host context.
Sometimes it's useful to apply styles based on some condition outside of the components view.
For example, a CSS theme class can be applied to the document body element.
And you want to change how your component looks based on that.
The following example applies a background color style to all h2 elements inside of the component.
Only if ancestor element has the CSS class theme light.
Now if you go to root element, add theme like class, you can see those styles.
And that's it.
Now let's see what is mg content.
Anti content uses the content projection to take HTML of another component and to displayed inside itself.
To me, it's similar to a film projector, where you have a slot to insert your content, which is going to be displayed on the screen.
It's a very powerful tool when you're building components intended for reuse.
I see it used extensively in frameworks such as NGO material.
When do you want to use energy content? anytime you want to inject any kind of HTML into a component, you can do so mg content.
I have two components child and root component to demonstrate this feature inside the child component, I will create some static content.
So I'll add an h2 title.
And below that title, I want to show that dynamic content.
So I will create an mg content tag.
With the MG content element in place.
Users of this component can now project their own message into the component.
To do that, let me insert a child inside of our root component and I will pass paragraph in a message.
As you can see, the energy content element is a placeholder that does not create a real DOM element.
Now, except single a component can have a multiple slots.
Each slot can specify a CSS selector that determines which content goes into that slot.
This pattern is referred to as multi slot content projection.
You can accomplish this task by using the Select attribute of Andry content inside of our child component.
add one more Angie content add, we can make our component to be like a question and answer card.
So in the first entry content, add question selector and put a second edgy content add answer selector.
Now, we can use the selectors to send different content.
In our route component, I will create a stream title request selector, and I will type this question text.
Below, I will create a paragraph get an answer selector, and I will type an answer text.
Also, there are a couple other ways to create multi slot content projection.
But we haven't covered conditionals yet.
As you can see, it's really easy to create reusable dynamic components.
This approach can be used for much more complex user interfaces.
But I showed you this simple example to understand the concept.
Next, let's discuss template statements.
A template statement is something that responds to an event raised by a target like an element component or directive.
So it's the same thing as if someone is calling you, which is an event and you're answering that phone call, which is the response and in our example, template statement.
It commits side effects as it changes the fields in the component.
Now, I will show you how to update class properties.
Using a template statement.
I have a blank component and in our template, I will create a Boolean property named show text in a value of false.
Below that, I will create a method named toggle text, it's not going to return anything at this point.
All we are going to do here is to toggle our show tax value on every method call.
Usually, we would use this kind of property to toggle the state in the view, but we haven't covered conditionals yet.
So in the template, I'm going to create a button which will respond on a click event and it will call this toggle method.
Below that I will adjust the state or show tax property.
And now when I click the button, you can see that it toggles the its value using template statement.
And in this example, toggle text is template statement.
This statement context may also refer to properties of the templates own context.
In the following example, toggle text takes the templates own event object as an argument.
If you log that object, you can see that it contains various information about a target and the event that occurred.
Passing arguments can be very useful when you're submitting the forms or looping through arrays, and you need to access a specific element.
One odd here is that the context of a template statement can be the component class instance, or the template.
Because of this, template statements cannot refer to anything the global namespace, such as window or document.
For example, template statement can call console log or math max.
pipes are simply functions you can use in your templates to accept any input value and return a formatted value.
In this case, you can see your data is untouched clay, which is ready to be mold.
At the beginning, it's not very nice or clear what it's for.
But with a little bit of crafting and molding, you can get the end result that you want.
Angular provides building pipes for typical data transformation like bait pipe, uppercase pipe, currency pipe, percent pipe, and similar.
In my app component, I will define a property with a value of new date.
If we just display our date object in our template, you can see what kind of format we get.
It's not very user friendly.
Now let's make it nicer.
To apply a pipe use the pipe operator within a template expression along with the name of the pipe, which is the date for the built in date pipe now this is my more readable.
One out here, date pipe is executed only when it detects a pure change to the input value.
A pure change is either a change a primitive input value such as string, number, Boolean or symbol, or a change object reference, such as date, array function, or object.
If you still don't like the output format of your data, you can fine tune it by using optional parameters.
There are predefined options like short or long, and others or you can customize it completely.
For example, Allbright for ease for a day in a week for EMS for a month, one lowercase D for an A in a month and one lowercase y for a year.
You can also change multiple pipes as well, you just add another pipe operator in a pipe name.
Now, we can create custom pipes as well.
Let's create a simple greetings by that will concatenate hello to pass name.
I'll use Angular Seelye to generate this file for me.
So type mg generate pipe and the name is reading's pipe.
In our pipe, we have boilerplate code generated.
You can see that pipe decorator has been imported with a name property, which we can use to call our pipe in our templates.
Also, there is a pipe transform interface which needs to be implemented.
This interface requires the transform method to be implemented.
And this method receives a value passed from a template.
In our case it will be a string.
And the second parameter is for optional params.
From pipe itself.
return type in our case is going to be a string.
Now all we're going to do here is to concatenate Hello wonder pastoring and return that.
Now in our template, we can call our custom pipe with the greetings pipe name that we defined, and I will pass world is our string.
Now that's how you create a custom pipes.
Angular pipes are very simple, but useful functionality provided by Angular, and you will use them a lot.
Once again for a detailed list of all pipes check the documentation link from the description.
Now let's discuss property binding.
Property binding moves a value in one direction.
So you can see is one way street.
You can go the other way.
It goes from class property to target element property.
Property binding in Angular helps you set values or properties of HTML elements or directives.
With property binding, you can do things as toggle button functionality set paths programmatically, and share values between components.
To bind the source property of an image element to a components property plays a target source in the square brackets followed by an equal sign, and then the property.
The property here is item image URL.
Declare the item image URL property in the class, in this case, app component.
A common point of confusion is between the attribute call span and the property call span.
Notice that these two names differ by only a single letter.
If you wrote something like this, you'll get the template parse our interpolation and property binding can set only properties, not attributes.
Instead, you'd use property binding and write it like this.
Another example is disabling a button when the component says that it's unchanged.
To disable advanced functionality depending on a boolean value, binding down disabled property to a property in the class.
That's true or false.
Because the value of the property is unchanged, it's true in the app component Angular disables the button.
Often interpolation in property binding can achieve the same result.
The following binding pairs do the same thing.
One odd evaluation of a template expression should have no visible side effects.
You shouldn't be assigning anything in the template expression or using increment or decrement operators.
If you had an expression that changed the value of something else that you were binding to, the change of value would be a side effect.
Now let's see but our attribute, class and style bindings.
Using these bindings, you can improve accessibility dynamically style your application in update classes on the fly.
First, let's talk about attribute binding.
Attribute binding in your your helps you set values or attributes directly.
It is recommended that you set an element property with a property binding whenever possible.
However, sometimes you don't have an element property to bind.
In those situations, you can use attribute binding attribute binding syntax resembles property binding, but instead of an element property between brackets, you proceed the name of the attribute with prefix ATR followed by a dot.
Then you set the attribute value with an expression that resolves to a string.
Another common use case for attribute binding is with the call span attribute in tables.
Mining the call span attribute helps you keep your tables programmatically dynamic.
Depending on the amount of data that your application populates a table with the number of columns their row span could change.
To use attribute binding with the TD attribute coursepack specify the call span attribute by using this syntax set attribute called span equal to an expression.
In this example, we bind the call span attribute to the expression one plus one.
This binding causes the table row to span two columns.
Sometimes there are differences between the name of property and an attribute.
Call span is an attribute of table row, while call span with the capital S is a property when using attribute binding, use call span with a lowercase s.
For more information on how to bind to the cost and property, check out the video about the property binding.
Now let's move to class binding.
You can use class binding to add and remove CSS class names from an elements class attribute.
To create a single class binding use the prefix class followed by a dot and the name of the CSS class.
Angular adds the class when the bound expression on sale is truthy.
And it removes the class when the expression is faulty.
With the exception of undefined.
To bind the multiple classes use class set to an expression.
The expression can be one of a space delimited string of class names.
An object class names as the keys and 30 old policy expressions as the values an array of class names.
With the object format, angular adds a class only if its associated value is truthy.
And finally, let's talk about style binding.
You can use style binding to set styles dynamically.
To create a single style binding.
Use the prefix style followed by a.in the name of the CSS style property, angular sets the property to the value of the bound expression, which is usually a string.
Optionally, you can add a unit extension like M or a percentage, which requires a number type.
You can write a style property name in either dash case, or camel case.
To toggle multiple styles, bind to the style attribute the style expression the style expression can be one of a string list of styles.
Or an object with style names is the keys in style values as the values and note that binding in the rate to style is not supported.
This time I'm talking about event binding.
Event binding allows you to listen for and respond to user actions such as keystrokes, mouse movements, clicks and touches.
It's similar to float fishing as you're waiting for a fish to take your bite.
And once it drips off, you respond quickly and strike.
To bind an event you use the angular event binding syntax.
The syntax consists of an event name within parentheses to the left of an equal sign in a template statement to the right.
In this example, the event name is click and the template statement is unsaved.
We can now define the unsaved method.
In RTS class.
And once we click our button, that event has been bound and our method is executed.
We can also bind to custom events.
To demonstrate that I'll create an item details component.
In this component, I'll create an event emitter with output decorator, which exposes our property to parent components.
Then I'll create a delete dummy method, which will just emit our property once we call it.
Now, I'll define a button and bind this method to a click event.
Next, I'll place our item details component in our app component.
And I will bind to the Delete request custom event that we just created.
I'm calling the lead item method.
And I'll use the event parameter to catch the string sent with this event.
And now I'll define the Delete item method narrow class and just log what we got.
And that's how you bind to custom event.
Now let's see two way binding connection.
Two Way binding is the concept of sharing and giving.
What you give is what you can expect from others.
Why to a binding to a binding gives components in your application a way to share data, use two way binding to listen for events and update values simultaneously between parent and child components.
Angular is two way binding syntax is a combination of square brackets in parentheses.
This syntax combines the brackets of the property binding with the parentheses of event binding.
I'll create a sizer component.
In our component, I will define a size value property in a size change event.
The size property is an input, so data can flow into the size or component.
The size change event is an output, which allows data to flow out of the size or component to the parent component.
Next, there are two methods that decrease the font size and ink to increase the font size.
These two methods use Resize to change the value of the size property within min max value constraints.
And to emit an event that conveys the new size value.
In the sizer component template, I'll create two buttons that each bind the click event to the ink and deck methods.
When the user clicks one of the buttons the sizer components, called the corresponding method.
Both methods ink and deck called the resize method with a plus one or minus one, which in turn raises the site change event with the new size value.
And below them, I'll add a label which displays the size property in dynamically a bit its own font size.
In our root app component, I'll include an app sizer component, and I will use two way binding to bind font size PX property to the size or component.
And below that, I'll add a div which will utilize this property to adjust its text size.
In the app component, one size PX establishes the initial size or component size value by setting the value to 16.
Clicking the button at this the app component font size px, the revised font size PX value updates style binding, which makes the display text bigger or smaller.
The two way binding syntax is shorthand for a combination of property binding and event binding.
The sizer component binding a separate property binding.
An event binding is as follows.
The event variable contains the data of the size or component size change event.
Angular assigns the event value to app component font size PX when the user clicks the buttons.
To use two way binding with Purim elements, we need mg model which I will cover in the forum section.
Next ones are template variables.
template variables helps you to use data from one part of a template.
In another part of a template.
It's a variable that is created in an indentifies a component or element within the template itself.
So it's like a phone number of a component, which you can use to call in case you need something from it.
With template variables, you can perform tasks such as respond to user input, or finally tune your applications for syntax.
In the template, you use the hash symbol to declare a template variable.
The following template variable phone declares a form variable when an input element, you can refer to a template variable anywhere in the components template.
Here a button further down the template refers to the form variable.
Now we can define the call form method and log the past value, which is the actual value of the input.
So what is the template variable scope, you can refer to a template variable anywhere within its surrounding template.
Structural directives such as Angie and Angie for which we'll cover in the later videos, or Angie template, act as a template boundary, you cannot access template variables outside of these boundaries.
So can we access variables in a nested template, an inner template that can access template variables that the outer template defines.
In the following example, changing the text in the input changes the value in the span because Angular immediately updates changes to the template variable ref one.
In this case, there's an implied Angie template around a span and a definition of the variable is outside of it.
So is the same thing as binding explicitly like this.
However, accessing that template variable from outside the parent template doesn't work is the same as writing the following.
And that's all for template variables.
Now, let's discuss directives is the same as if you are a CEO of the company.
And you are giving directives to your employees how to behave in what to do in certain situations.
What are directives.
directives are classes that add additional behavior to elements in your Angular application.
with Angular built in directives, you can manage forms, lists, styles, and what users see.
The different types of Angular directives are as follows.
Components directives with a template this type of directive is the most common directive type attribute directives.
directives that change the appearance or behavior of an element component or another directive.
Structural directives, directives that change the DOM layout by adding and removing DOM elements.
Today, we are talking about built in attribute directives.
Attribute directive listens to and modify the behavior of other HTML elements, attributes, properties, and components.
Many angii modules such as router module and forms module, they find their own attribute directives.
The most common attribute directives are as follows.
mg class adds and removes a set of CSS classes and G style adds and removes its set of HTML styles.
And model adds two way data binding to an HTML form element.
How to add and remove classes with NGO class.
You can add or remove multiple CSS classes simultaneously with mg class.
To add or remove a single class use class mining rather than entry class.
When the element you'd like to style, add Angie class and set it equal to an expression.
In our class.
Let's define you special as true Because is special is true and reclass applies the class of special to the diff.
To use NGO class with a method add method to the component class.
In the following example, set current classes sets the property current classes with an object that adds or removes three classes based on the true or false state of three other component properties.
Each key of the object is a CSS class name.
If a key is a true and your class as the class if a key is false, and re class removes the class.
Boolean values are hard coded just for demonstration.
In the template, added the N g class property binding to current class to set the elements classes.
And now we can preview our classes.
Now let's talk about mg style.
You can use mg style to set multiple inline styles simultaneously based on the state of the component.
To use edgy style and the method to component class.
Add empty object current style.
In the following example, set current style says the property current styles with an object that defines three styles to set elements styles, and an energy style property binding the current styles.
For this use case, angular applies the styles upon initial annotations.
And in case of changes.
To do this, the full example called set current styles initially with NGOs in it.
And the last one in today's video is NGO model, you can use the NGO model directive to display a data property and update that property.
When the user make changes.
Input forms module and add it to NGO modules import list.
I'll create a label and an input for this example.
Add an mg model binding of an HTML form element and set it equal to the property here its name.
Now, if you define property inside of our component class, you can see how mg model directive adds two way data binding to our input.
This mg model syntax can only set a data bound property.
When you write an Angular component, you don't need a value accessor or mg model if your name, the value and even properties according to Angular to a binding syntax.
And that's all for this section.
In this section, we are continuing with Angular directives.
Let's build attribute directive.
Let's create a file highlight that directive.ts which is the convention that you always should follow.
Next, import directive decorator from core and implement that decorator with selector property.
For me, it's going to be app highlight.
Next, we want to export our class.
And the last thing we want is to import that in our declarations array in app module.
That's our directive boilerplate code, which can also get with the command mg generate directive highlight.
Import element ref from Angular core.
Element ref grants direct access to the host DOM element through its native element property.
And element ref in the directive constructor to inject a reference to host DOM element, the element to which you apply app highlight.
Add logic to the highlight directive class that sets the background to yellow.
To use the highlight directive add a paragraph element to the HTML template with the directive as an attribute.
Angular creates an instance of highlight directive class and inject in the reference to the paragraph element into directive constructor, which has the P elements background style to yellow.
Now, let's see how to detect when a user mouse's into or out of the element and to respond by setting or clearing the highlight color.
Import host listener from Angular core Add it to event handlers that respond when the mouse enters or leaves, each with a host listener decorator.
With the host listener decorator, you can subscribe to events of the DOM element that hosts an attribute directive.
The paragraph in this case, the handlers delegate to a helper method highlight that says the color on the host DOM element L.
The background color appears when the pointer hovers over the paragraph element and disappears as the pointer moves out.
Now, let's see how we can make the directive dynamic to be able to use it at different places with different colors.
In highlight directive Ts File, Import input from Angular core, add an app highlight input property.
The input decorator adds metadata to the class that makes the directive app highlight property available for binding.
In app component Ts add a color property to the app component.
To simultaneously applied the directive and the color.
Use the property binding with the app highlight directive selector setting to equal to color.
The app highlight attribute binding performs two tasks applies the highlighting directive to the paragraph element and sets directive highlight color with the property binding.
And that's all for this one.
This is the last section about directives.
So let's see what are structural directives.
Structural directives are responsible for HTML layout.
They shape or reshape the dome structure, typically by adding removing and manipulating the host elements to which they're attached.
This section introduces the most common built in structure directives.
mg conditionally creates or disposes of sub views from the template and you for repeat a note for each item in a list.
And you switch a set of directives that switch among alternative views.
You can add or remove an element by applying an mg if directive to a host element.
When Ngf is false, angular removes an element and its descendants from the DOM.
Angular then disposes of their components, which frees up memory in resources to add or remove an element by the engine if they condition expression such as is active in this example.
vendor is active expression returns a true value Ngf as the div to the DOM.
When the expression is false, he Ngf removes the dim from the DOM.
That's simpler right.
Now let's talk about mg four.
You can use the NG g4 directive to present a list of items.
Let's create an array of objects with the name property in it.
Define a block of HTML that determines how Angular renders a single item.
to list your items assigned the shorthand lead item of items to energy for the string lead item of items instructs Angular to do the following.
Store each item in the items array in the local item looping variable, make each item available to the template HTML for each iteration.
Translate lead item of items into energy template around the host element.
Repeat the energy template for each item in the list.
By the way, you can get the index of energy for in a template input variable in use it in the template in the NG g4, add a semicolon and let i equals to index to the shorthand.
The following example guys the index in a variable named I in these days it within the item name.
And just switch displays one element from among several possible elements based on a switch condition.
Angular puts only the selected element into the DOM.
And g switch is a set of three directives.
And you switch an attribute directive that changes the behavior of its companion directives and j switch case structure directive that adds its element to the DOM.
When it's bound value equals to switch value and removes its bound value when it doesn't equal the switch value.
Andrey switch default structural directive that adds its element to the DOM.
When there is no selected energy switch case, I'll modify the items array to be just a single item.
On an element such as I do, add Angie switch bound to an expression that returns the switch value such as a name.
Though the name value in this example is a string, the switch value can be of any type bind to mg speech case and mg speech to default on the LMS for the cases.
And now depending on the value of the item name rendering on the page changes.
If it didn't provide a case for the name value, default will be executed.
Next, we are discussing dependency injection.
dependencies are services or objects that a class needs to perform its function.
dependency injection, or di is a design pattern in which a class request dependencies from external sources rather than creating them.
You can look at it as if you're adding an extension to your browser, or adding an app to a phone.
Once you add it, you provide yourself with the new functionalities and features nice extension.
Let's create a service which we can inject in our components.
Create a new file with the name log.service.ts.
Import injectable decorator from Angular core.
And then for provided in metadata add root value, which means that we are going to provide the service in the root of the application and that is visible throughout the application.
export our log service class and inside of this service, we want to add our log message method, which will just log past messages.
For clarity in meeting ability, it is recommended that you define components and services in separate files now inject our log service into the app module file in providers array.
injecting service results in making them visible to a component.
to inject a dependency in components constructor supply a constructor argument with dependency type.
The following example specifies the lock service, the app component constructor to type of log service is log service.
Now we can reference our log service in our component and call our method from it should pass our message and as you can see it's being executed.
We can use this approach to inject third party libraries in other modules that are available in the angular framework.
So let's inject render to module which is used for custom rendering and updating the DOM.
Import render to from Angular core and injected inside the constructor.
Also, we will need element ref, which we can use for referencing our DOM elements, or the host component in our case.
Now inside the NG on init lifecycle, call the set style method of the renderer and set the color of host native element to red.
This method changes the color of our components tax.
And as you can see, with the dependency injection, we get access to more features and methods.
That's all there is to it.
Next is very important topic.
The angular router is a core part of Angular platform.
It enables developers to build single page applications with multiple views.
In the navigation between these views.
We can compare routing of our obligations with navigating a plane.
Pilot says the flight coordinates in our case route path, and the plane lands on the desired location or desire page in our app.
Oftentimes, planes carries goods or cargo and routes carry params info in data.
And unfortunately, some things do get crashed or lost.
And for route sometimes we get 404 To use the angular router, an application needs to have at least two components so that it can navigate from one to the other.
To create a component using the COI, enter the following at the command line, where first is the name of your component, and G generate component.
First, repeat this step for a second component or give it a different name.
Here the new name is second.
This guide works with a CI generated Angular application.
If you're working manually, make sure that you have base href would slash in the head of your index HTML file.
This assumes that the app folder is the application route and that uses slash create a new module for routing named app dash routing dot module.
We find const routes which is type of routes.
Here we will define our paths and components.
Inside NGO module imports array add router module in call for route module it routes passed as argument, then export the router module so it can be imported into the route module.
At the end, define the app routing module class imported app routing module into app module and add it to the imports array.
Now define your routes in your routes array.
The first property bath defines the URL path for the route.
The second property component defines the component that Angular should use for the corresponding path.
Now that you have defined your routes, you can add them to your application.
First, add links to the two components.
assigned an anchor tag that you want to add the rod to the router link attribute.
Set the value of the attribute to the component to show when a user clicks on each link.
Next, update your component template to include router outlet.
This element informs Angular to update the application view with the component for the selected route.
You can add router link active activity if you want to style active link.
One Note the order of routes is important because the router uses a first match wins strategy when matching routes.
So more specific routes should be placed about less specific routes.
Often is a user navigator application, you want to pass information from one component to another.
To do so you use the activated route interface.
First input router activated route in para map to your component.
inject an instance of activated route by adding it to your applications constructor.
Update the NGO own init method to access the activator route and track the ID parameter.
Now we need to adjust our routes to pass the ID params as well.
In that add semi colon and name of your parameter.
And then we can add ID values to our links.
That's how you pass in retrieve data from one component to another.
A well functioning application should gracefully handle when user attempts to navigate to a part of your application that doesn't exist.
To add this functionality to your application.
You set up a wildcard route.
The angular route selects this route anytime the requested URL doesn't match any router paths.
To set up a wildcard route, add the following code to your routes definition.
For the component property, you can define any component in your application.
Common choices include an application specific page not found component.
But here I'm just redirecting to the first component.
And now if you navigate to any random path, it will always give us first component.
As your application grows more complex, you may want to create routes that are relative to the component other than your route component.
These types of nested routes are called child routes.
This means you're adding a second router outlet to app because it is in addition to the router outlet in app component.
In this example, there are two additional child components child a and child b.
here first component has its own nav, and a second router outlet in addition to the one in app component.
Also, I'm going to create two child routes with the router links of child a child B and give it a second router link.
Now I'll create two additional component with Angular ccli in named their child a component and child B component.
Each other route is like any other route, in that it needs both a path and a component.
The one difference is that you place child routes in a children array within the parent route.
Now if you navigate to any of child routes, we get the corresponding child component.
Use route guards to prevent users from navigating to parts of an application without authorization.
The following route guards are available in Angular can activate connect to a child can deactivate, resold and can load create a service for your guard.
mg generate guard your guard.
In your guard class implement the guard you want to use the following example users can activate to guard the route.
Now depending on your logic, it can return true or false.
Usually it's checks if the user is logged in, or does he have privileges to access the page in your routing module, use the appropriate property in your routes configuration here can activate tells the router to mediate navigation to this particular route.
Now, if you set the guard too fast, we can't access the route.
Otherwise, we can.
And that's all for routing for this section.
After this one, we're covering one even more important concept, and that is angular forms.
Let's start off with template driven forms.
I know it sounds impossible, but there were times when there was no internet or even computer.
So in those times, we had to fill out good old paper forms when we wanted to visit a doctor or to apply for various personal documents.
So web forms are nothing different except their digital.
NGO supports two design approaches for interactive forms.
template driven forms are suitable for small or simpler forms.
While reactive forms are more scalable and suitable for complex forms.
This tutorial shows you how to build a form from scratch.
First, import forms module in your app root module.
Let's first build our bad class which defines a data model reflected in our form.
High will have three properties ID name is PC.
Now let's import our class in the app component.
Define a species in species array.
Now create a model from the battle.
Last in pass the values for our path.
Here we're using dummy data.
But in your real app, you would use a service to get the data from the API and to save it.
Also, let's add submitted property, which will change depending on the state of the form and on submit method.
Next in our HTML file, we will create a form that reflects our data model.
Create a form and inside two divs for two fields.
First, we'll be naming input.
And I'm adding a label and required attribute to our input.
And the second one will be a cell Act, which will loop through an array of species to show all the values from the array.
Same as for input, I'm adding a label for our select.
And also I'll add the required attribute.
Then I will use mg for tillow to do all the values and display them.
If you run the application right now, you'll see the list of species in the selection control.
The input elements are not yet bound to data values or events.
So they are still blank and have no behavior.
The next step is to bind the input controls to the corresponding bad properties with two way data binding so that they respond to the user input by updating the data model, and also respond to programmatic changes in the data by updating the display.
The NGO model directive declared in the forms module, lets you bind controls in your template driven form to properties in your data model.
Add the energy model directive using two way data binding syntax for the name use model dot name.
And for species use model dot species value.
When you use Angie model on element, you must define a name attribute for that element.
Angular uses the assigned name to register the element with the energy form directive attached to the parent form element.
So in order to register our form, add a template reference variable use the value of MG form.
The platform template variable is now a reference to the NG g form directive instance that governs the form as a whole.
In order to test our application plays the model object in our template with a JSON pipe.
Now if you update your foreign films, you will see that model is being updated.
Now the user should be able to submit this form after filling it, create a submit button on the bottom.
the submit button at the bottom of the form does nothing on its own, but it does trigger us form submit event because of its type Submit.
To respond to this event.
Take the following steps.
bind the forms mg submit event property to the platform component.
on submit method.
Use the template reference variable bedform.
To access the form that contains the submit button and create an event binding.
You will bind the form property that indicates its overall validity to the Submit buttons disabled property.
run the application now.
Notice that the button is enabled.
Although it doesn't do anything useful yet.
Delete the name value.
This file is the required rule so disable the submit button.
The show I response to form submission you can hide the data entry area in this place something else in its place.
Wrap the entire form in a deal in bind it's hidden property to the app component submitted property.
The main form is visible from the start because the submitted property is false until you submit the form as this fragment from the app component chose to show something else while the form is in submitted state add the following HTML below the new div wrapper add the properties that you updated in the edit button.
If the user wants to update the fields again.
And now let's preview how it works.
That's all about template driven forms.
Now in the next section, we're going to see how we can take more control of our forms and how to create reactive forms.
Reactive forms provide a model driven approach to handling form inputs, whose values change over time.
Each change to the form state returns a new state, which maintains the integrity of the model between changes.
Let's add basic form control.
To use reactive form controls, import reactive forms module from Angular forms package and added to your NGO modules import array.
To register a single form control, import a form control class and create a new instance of form control to save as a class property.
Use the constructor of form control to set its initial value, which in this case is an empty string.
By creating these controls in your component class, you get immediate access to listen for update and validate the state of the form input.
After you create a control in the component class, you must associate it with a form control element in the template Are they the template with a form control using the form control binding provided by form control directive, which is also included in the reactive forms module.
Using the template binding syntax, the form control is now registered to the name input element in the template, you can display the value in the following ways through the value changes observable very can listen for changes in the form of value in the template using async pipe or in the component class using the subscribe method or with the value property, which gives you a snapshot of the current value.
The following example shows you how to display the current value using interpolation.
In the template.
The displayed value changes as you update the form control element.
Reactive forms have methods to change it controls value programmatically, which gives you the flexibility to update the value without user interaction.
The following example as a method to the component class to update the value of the control to Nancy using the set value method.
Update the template button button to simulate a name update.
When you click the Update name button, the value entered in the form control element is reflected as its current value.
The form model is the source of truth for the control.
So when you click the button, the value of the input is change within the component class, overriding its current value.
Form stabilty contains several related controls.
Reactive forms provide two ways of grouping multiple related controls into a single input form.
First way of form group defines a form with a fixed set of controls that you can manage together.
And second way of form array defines a dynamic form where you can add and remove controls at runtime.
import the form group and form control classes from the angular forms package.
Create a property in the component class name profile form, and set the property to a new form group instance.
to initialize the form group provide a constructor with an object of named keys mapped to their control.
For the profile form add to form control instances with the names first name and last theme.
The individual form controls are not collected within a group.
After you define a model, you must update the template to reflect the model in the view.
I'm adding two inputs and two labels that match our model.
The form control name input provided by the form control name directive binds each individual input to the form control defined in the form group.
The forum comm directive lessons for the Submit event, immediate buy the form element and emits an mg submit event that you can bind to a callback function.
Add an mg submit event listener to the form tag with the on submit callback method.
The onsubmit method captures the current value of profile form.
Here, you will just log the form value.
The submit event is emitted by the form tag using the native Dom event, you trigger the event by clicking a button in submit type.
This allows the user to press the Enter key to submit the completed form.
Add a button to the bottom of the form to trigger the form submission.
And that's all for reactive forms.
In the next section, we're going to see how we can improve our forms.
So in this section, we're covering form validation.
This tutorial will show you how to validate user input from the UI and display useful validation messages in both reactive and template driven forms.
Anything that you want to store to your database needs to have multiple levels of validation and AC validation the same as if you're at an audition, or job interview something or whether someone is presenting to you and you decide will he pass or not.
To add validation to a template driven form, you add the same validation attributes as you would with native HTML form validation.
Angular uses directives to match these attributes with validator functions in the framework.
Every time the value of a form control changes, anger runs validation, and generates either a list of validation errors that results in an invalid status or not.
It results in a valid status.
I'll create a name string field inside of our component class.
Then in our HTML file, I'll add an input text field with required attribute me length of four.
I'm binding name input property to energy model, and I'm exporting energy model to a local variable called main engine model mirrors many of the properties of its underlying form control instance.
So can use this template to check for control states such as valid and dirty.
The mgf of the div element reveals a set of nested messages they have, but only if the name is invalid, and the control is either dirty or touched.
Each nested they have can present a custom message for one of the possible validation errors.
These are messages for acquired admin lead.
Now if we type something and leave the field empty, we will get the validation error message.
And the same goes if we enter value less than four characters long.
In a reactive form, the source of truth is a component class.
Instead of adding validators through attributes in the template, you add validator function directly to the form control model in the component class.
The same built in validators that are available as he was in template driven forms, such as required and min length are all available to use as functions from the validator class.
To update the validation form to be a reactive form, use some of the same built in validators.
In this example, the name control sets up to a built in validators validators required in validators min length.
These validators are synchronous, so they are passed as the second argument.
Notice that you can support multiple validators by passing the functions in as an array.
This example also adds a getter method.
In a reactive form, you can always access any form control through the get method on its parent group.
But sometimes it's useful to define and getters.
It's shorthand for the template.
In our template, add form group to our form.
And now, only thing that we need to change in our template to make it reactive is to remove Angie Murrell and to bide our name control to form control name.
This forum differs from the template driven version in that delong exports any directives.
Instead, it uses the name gatter defined in the component class, known as the required attribute is still present in the template.
Although it's not necessary for validation, it should be retained for accessibility purpose.
We finally came to the end of this long tutorial, and we're going to cover communication using HTTP client.
Imagine that you're running a TV station or a newspaper.
And what if you lose communication to reporters, you would end up with a blank newspaper or no news broadcasts is the same thing with web apps.
Without backend communication, our apps will be bad without informations or instructions on the back end.
Most front end applications need to communicate with a server over HTTP protocol to download or upload data and access other backend services.
Before we can use HTTP client, you need to import Angular HTTP client module.
Most apps do so in the root app module.
Let's create data service.
Most common use case is to inject HTTP client into service.
In use it throughout the application, you can then inject HTTP client service as a dependency of an application class, as shown in this example.
Now let's see how we can fetch data from a server.
To do that, we're going to use HTTP client get method.
First inject HTTP client into our service.
Then create get data method and inside of this method will fetch our data.
the get method takes two arguments the endpoint URL from which to fetch and an options object that you use to configure the request to add things like parameters to your request.
For this tutorial, I found a free cocktail API service.
The link will be in the description box below, enter the URL, and no additional parameters are required in this case.
Now in our app component, we inject the data service in the constructor inside of MG on init method, let's call our get data method.
Because the service method returns an observable, the component subscribes to the methods return value.
I'm just gonna console log in.
And that's how you get data from the server.
In an ideal world, everything works as a magic.
But we don't live in an ideal world, fortunately, and we lose connection with API sometimes.
So we need to handle errors when they come up.
If the request fails on the server, HTTP client returns an error object instead of a successful response.
Let's add a pipe on our get method and use cash error to catch it.
I'm going to log the error for development purpose and return throw error with some message.
They should be used in your obligation to show the user that his request has failed.
Without notification, they wouldn't know what's happening.
And don't forget to import missing packages.
Now we can change the URL to break the request.
And to see the error, we usually don't want to see this view in our obligations.
But we need to be ready for that when it happens.
HTTP client besides get also has a POST method for submitting data to server.
For example, if you are submitting a form, we have delete requests for deleting data from database obviously, a pull request which replaces a resource with updated data.
Now, most of the API's require an authentication key with their requests.
So let's see how we can add that I found this Lord of Rings database which requires an auth key.
Let's create HTTP options object with the headers property.
This property will be a new HD We had this object, and we will pass two properties.
Content Type is application JSON, which means that we're using JSON as content and authorization, where we enter our API key barrier is type of authorization, and follow by key.
In order to get your personal key you need to register link is in the description box below.
Now, are they the API endpoint.
And if you try to call it without passing the HTTP options, you can see that we get an error.
What if we add authorization the request is successful.
Congratulations, you watch all the way through the end.
This was very long tutorial and I hope you learned a lot of new things.
Also, don't forget to subscribe to Free Code Camp.
And if you want to see more tutorials like this, don't forget to check out my channel.
My name is Slobodan, and I'll see you guys in one of the next videos or tutorials.