Angular Tutorial for Beginners – Web Framework with Typescript Course

Angular Tutorial for Beginners – Web Framework with Typescript Course
Spread the love

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 gonna 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 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 english versions beyond  2 plus are generally known as angular  only  the very first version of angular is  known as angularjs  so why angular  well because it’s supported on various  platforms we have mobile desktop native  it’s powerful modern has nice ecosystem  and it’s just cool not convinced  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  when an angular application is crafted  properly  you don’t end up with a tangle of  classes and methods that are harder 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  it’s javascript but better  angular is built with typescript which  in turn relies on js es6  you don’t need to learn a totally new  language but you still receive features  like static typing interfaces classes  name spaces decorators etc  no need to reinvent the bicycle  with angular you already have lots of  tools to start crafting the application  right way 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 asynchronous http  requests of 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 tie  coupling between various components of  the application  injection happens in node.js style and  you may replace various components with  ease  all dawn manipulation happens where it  should happen  with angular you don’t tightly couple  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 identifies 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 ng modules  every angular app has at least one  angular module class the road module  conveniently named app module  while the road 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 a workflow or a  closely related set of capabilities  an angular module whether a route or a  feature is a class with a ng 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 typical 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 based 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 a  css selector that defines how the  component is used in a template and  optionally css styles applied to the  component  a component must belong to an ng 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 we are able to reuse our code so we  don’t duplicate it  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 cli and create an  angular workspace with initial  application  if you don’t have a project you can  create one using ng new project name  where project name is the name of your  application  although the angular cli is the easiest  way to create an angular component in  this tutorial we will create our  component manually  to create a new component navigate 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 as an angular  component and provides metadata that  decides how the component is used at  runtime  choose css selector for the component  this is the tag which you will be using  in your template files to render your  component  define 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 defined the  styles for your components template in a  separate file again i will use it within  the file to declare the styles for a  component in a separate file add a style  urls property to the it 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 ejection but i’ll talk more  about these in the next video  now  all the public properties that you  define in the class are accessible in  the html template and this is one of the  most powerful things here  i’ll create a tiler 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 which you can reuse across  your app  in this section we are talking about  life cycle hooks there are special  functionality in angular that allows us  to hook into and run code at a specific  lifecycle event of a component or  directive you can look at them as phases  of component life like every living  being has they get born they change they  grow and eventually they die with life  cycle hooks you can gain better control  of our application  when do we want to use them  for example if you want to fetch some  data and display it in your component  you will do that inside of ngoninit  lifecycle when it 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 ng on destroy  lifecycle hook just before component  gets destroyed  this is the list of all hooks in exact  order how they get initialized but most  used ones are on init on changes and on  destroy  let’s implement the ngoninit hook as you  will be using this hook the most  first import unit 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 ng to the interface name and you  will get the method needed for  implementation  so in this case it’s ng on init we will  create a simple function for logging  some values to the console now i will  create a property that will save that  function so that we can clean it up at  the end  in the ng 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 ng on destroy hook  import ondestroy interface and place it  next to uninit  now create the ng on destroy 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 can 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 the data from a test  script 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 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 value is 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  template expressions are similar to  javascript except you can’t use  assignments also operators such as new  type of or instasoft  you can’t use chaining expressions  decrement or increment operators and  some of the es 2015 plus operators  expressions can also invoke methods so  let’s create one  name of our method will be get min  and in this method we are returning  value for displaying it in our template  in this case it will be a minimum value  couple 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  let’s learn how to communicate between  the components  an angular application usually consists  of many separated 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 fluent 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 child provider using services  and template outlet  in this tutorial i’m going to cover the  first two ways as we haven’t covered  services yet and the template outlet is  a little bit advanced  first use case is when we want to send  data from parent to child using input  decorator  input decorator takes the value pass  from parent and stores that value in the  child property  let me create two components using  angular cli  i will run the following commands  ng generate component parent  and ng generated component child  in our child component i will import  input decorator and name our input as  child message of type string  in the 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 as a doorway through  which data can travel from the child to  the parent  this approach is ideal when you want to  share data that occurs on things like  button click form entries and other user  events  to raise 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 import output  decorator and event emitter  we declare a message event variable with  output decorator and set it to equal to  a new event emitter  then we create a function named  sendmessage that calls a mid 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 way for  passing data  hence 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  a child won’t be available to give  access until the view 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 and after view init  from angular core and our child  component  for our view child decorator pass our  child component as an argument and name  it as child  next implement after view init life  cycle hook  by the way to learn more about angular  hooks check the part 2 of this video  series  inside the ng after view unit 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  [Music]  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 to 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  inline 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 defines some css for this  component  you can load styles from external css  files  by adding a styles url property to a  component’s 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 link tags into the  component’s 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  the variables  reminder these styles apply only to this  component  so if you have h1 tag in a child or  parent component it won’t be applied  there  by default view encapsulation is set 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 define  more global styles in the angular json  file  another thing is that if you’re building  with the cli you can write style files  in sas less or stylus and specify those  files in the component style urls  metadata with 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 as 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 could 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 elements has the css  class theme light  now if you go to root element and add  theme light class you can see those  styles  and that’s it  [Music]  now let’s see what is ng content  ng content uses the content projection  to take html of another component and to  display it 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 ng material  when they want to use ng content  anytime you want to inject any kind of  html into a component you can do so with  ng 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 h2 title  and below that title i want to show the  dynamic content  so i will create an ng content tag  with the ng 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 a paragraph with a  message  as you can see the ng 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 ng content  inside of our child component add one  more ng content tag  we can make our component to be like a  question and ask a card  so in the first engine content add  question selector and for the second ng  content add answer selector  now we can use these selectors to send  different content  in our root component i will create h3  title with a question selector and i  will type this question text  below i will create a paragraph with an  answer selector and i will type an  answer text  also there are couple other ways to  create multislot 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  [Music]  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 blend component and in our  template i will create a boolean  property named show text be the 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 text 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 just display our show  text property  and now when i click the button you can  see that it toggles its value using  template statement and in this example  toggle text is template statement  this statement context may also refer to  properties of the template’s own context  in the following example toggle text  takes the template’s own event object as  an argument  if you log that object you can see that  it contains various information about  the 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 note 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’t call  console.log or mathmax  pipes  pipes are simply functions you can use  in your templates to accept an input  value and return a format head value  in this case you can see your data as  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 results that you wanted  angular provides built-in pipes for  typical data transformation like date  pipe uppercase pipe currency pipe  percent pipe and similar  in my app component i will define a date  property with the 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  much more readable one out here date  pipe is executed only but it detects a  pure change to the input value a pure  change is either a change to 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 date 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 i’ll write four e’s for a  day in a week four m’s for a month  one lowercase d for a day in a month and  one lowercase y for a year  you can also chain multiple pipes as  well  you just add another pipe operator and a  pipe name  now we can create custom pipes as well  let’s create a simple greetings pipe  that will concatenate hello to past name  i’ll use angular cli to generate this  file for me so  type ng  generate pipe and the name is greetings  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 are going to do here is to  concatenate hello on the path string 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 as  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  [Music]  now let’s discuss property binding  property binding moves a value in one  direction so you can see it as one-way  street  you can go the other way  value 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 sugar button functionality set paths  programmatically and share values  between components  to bind the source property of an image  element to a component’s property  place the 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’d  get template parse error  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 a button’s functionality  depending on a boolean value binding dom  disable property to a property in the  class that’s true or false  because the value of the property is  unchanged it shows in the app component  angular disables the button  often interpolation and property binding  can achieve the same result  the following binding pairs do the same  thing  one note  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  [Music]  now let’s see what are attribute class  and style windings  using these bindings you can improve  accessibility dynamically style your  application and update classes on the  fly first let’s talk about attribute  binding attribute binding in angular  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 attr 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 that a row span  could change  to use attribute binding with the td  attribute callspan specify the callspan  attribute by using this syntax  set attribute call 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 call spam 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 falsy  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  and objective class names as the keys  and 30 all 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 dot 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 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 as the  keys and style values as the values  and note that binding an array to style  is not supported  [Music]  this time i’m talking about event  binding event binding allows you to  listen for and respond to user actions  such as keystroke 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  this syntax consists of an event name  within parentheses to the left of an  equal sign and a template statement to  the right  in this example the event name is click  and the template statement is on save  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 delete item method and i’ll  use the event parameter to cache the  string sent with this event  and now i’ll define the delete item  method in our class and just log what we  got  and that’s how you bind to a custom  event  [Music]  now let’s see two-way binding in action  two-way binding is the concept of  sharing and giving what you give is what  you can expect from others  why two-way binding toy 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’s  two-way binding syntax is a combination  of square brackets and 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 sizer component  the size change event is an output which  allows data to flow out of the sizer  component to the parent component  next there are two methods deck to  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 component  calls the corresponding method  both methods ink and deck called the  resize method with a plus one or minus  one which in turn raises the sign change  event with the new size value  and below them i’ll add a label which  displays size property and dynamically  updates 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 sizer component  and below that i’ll add a div which will  utilize this property to adjust its text  size  in the app component font size px  establishes the initial sizer component  size value by setting the value to 16.  clicking the button updates the app  component font size bx  the revised font size px value updates  the 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 has separate  property binding  and event binding is as follows  the event variable contains the data of  the sizer 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 form  elements we need ng model which i will  cover in the form 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 and  identifies a component or element within  the template itself so it’s like a phone  number of a component which you can use  to call it in case you need something  from it  with template variables you can perform  tasks such as respond to user input or  finely tune your applications form  syntax  in the template you use the hash symbol  to declare a template variable  the following template variable phone  declares a phone variable on 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 font 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 ngif and  ng4 which we’ll cover in the later  videos or ng 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 inline template 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  ref1  in this case there is an implied ng  template around the span and the  definition of the variable is outside of  it  so it’s the same thing as writing it  explicitly like this  however accessing a template variable  from outside the parent template doesn’t  work  it’s the same as writing the following  and that’s all for template variables  now let’s discuss directives  it’s the same as if you are a ceo of the  company and you are giving directives to  your employees how to behave and 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 type 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 ng modules such as router module  and forms module define their own  attribute directives the most common  attribute directives are as follows  ng-class adds and removes a set of css  classes  ng style adds and removes a set of html  styles  ng model adds two-way data binding to an  html form element  how to add and remove classes with  ng-class  you can add or remove multiple css  classes simultaneously with ng-class to  add or remove a single class use class  binding rather than ng class  on the element you’d like to style add  ng class and set it to equal to an  expression  in our class let’s define e-special as  true  because e-special is true energy class  applies the class of special to the div  to use ng 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 k is a true energy class adds the  class  if a key is false energy class removes  the class  boolean values are hard coded just for  demonstration  in the template add the ng class  property binding to current class to set  the elements classes  and now we can preview our classes  now let’s talk about ng style  you can use ng style to set multiple  inline styles simultaneously based on  the state of the component  to use ng style add the method to  component class  add empty object current style  in the following example set current  styles sets the property current styles  with an object that defines three styles  to set element styles add an ng style  property binding to current styles  for this use case angular applies the  styles upon initializations  and in case of changes  to do this the full example calls set  current styles initially with ng on in  it  and the last one in today’s video is ng  model  you can use the ng model directive to  display a data property and update that  property when the user make changes  import forms module and add it to ng  modules import list  i’ll create a label and an input for  this example  add an ng 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 ng model directive adds two-way  data binding to our input  this ng-model syntax can only set a  data-bound property  when you write an angular component you  don’t need a value accessor or ng model  if you’re named the value and even  properties according to angular 2a  binding syntax and that’s all for this  section  in this section we are continuing with  angle directives let’s build attribute  directive  let’s create a file highlight dot  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  the last thing we want is to import that  in our declarations array in app module  that’s our directive boilerplate code  which you can also get with the command  ng generate directive highlight  import element ref from angular core  element ref grants direct access to the  host dom element through its native  element property add element ref in the  directives 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 injects in reference  to the paragraph element into directives  constructor which sets the p element’s  background style to yellow now let’s see  how to detect when a user mouses into or  out of the element and to respond by  setting or clearing the highlight color  import host listener from angular core  add two event handlers that respond when  the mouse enters or leaves each with the  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 sets 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  inputs 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 yes add a color  property to the app component  to simultaneously apply the directive  and the color use the property binding  with the f highlight directive selector  setting to equal to color  the amp highlight attribute binding  performs two tasks applies the  highlighting directive to the paragraph  element  and sets directive highlight color with  a property binding  and that’s all for this one  [Music]  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 dom structure  typically by adding removing and  manipulating the host elements to which  they are attached  this section introduces the most common  built-in structural directives  ngif  conditionally creates or disposes of  subviews from the template  mg4  repeat a node for each item in a list  ng switch  a set of directives that switch among  alternative views  you can add or remove an element by  applying an ngif directive to a host  element  when ngif is false  angular removes an element and its  descendants from the dom  angular then disposes of their  components which frees up memory and  resources  to add or remove an element bind ng if  to a condition expression such as is  active in this example  when the is active expression returns a  true value ngif adds the div to the dom  when the expression is falsy ngf removes  the dim from the dom  that’s simpler right  now let’s talk about ng4  you can use the ng4 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 let item of items to ng4  the string led 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 let item of items into ng  template around the host element  repeat the ng template for each item in  the list  by the way you can get the index of ng4  in a template input variable and use it  in the template  in the ng4 add a semicolon and let i  equals to index to the shorthand  the following example gets the index in  a variable named i and displays it  within the item name  and the last directive which we are  going to talk about  is switch  like the javascript switch statement  ng-switch displays one element from  among several possible elements based on  a switch condition  angular puts only the selected element  into the dom  ng switch is a set of three directives  ng switch an attribute directive that  changes the behavior of its companion  directives  ng switch case  structural directive that adds its  element to the dom when its bound value  equals the switch value and removes its  bound value when it doesn’t equal the  switch value  ng switch default structural directive  that adds its element to the dom when  there is no selected ng switch case  i’ll modify the item’s array to be just  a single item  on an element such as a div add ng  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 ng switch case and ng switch  default on the elements for the cases  and now depending on the value of the  item name rendering of the page changes  if we didn’t provide a case for the name  value default will be executed  [Music]  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 requests  dependencies from external sources  rather than creating them  you can look at it as if you are adding  an extension to your browser or adding  an app to your 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.ds  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 it’s 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 and maintainability 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 log  service in the app component constructor  the type of log service is log service  now we can reference our log service in  our component and call our method from  it  we should pass our message and as you  can see it’s being executed as expected  we can use this approach to inject  third-party libraries and other modules  that are available in angular framework  so let’s inject render 2 module which is  used for custom rendering and updating  the dom  import renderer 2 from angular core and  inject it inside the constructor  also we will need element graph which we  can use for referencing our dom elements  or the host component in our case  now inside the ngo edit 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 text and as you can see with  the dependency injection we get access  to more features and methods  that’s all there is to it  [Music]  next is very important topic  routing the angular router is a core  part of angular platform it enables  developers to build single page  applications with multiple views and  allow navigation between these views  we can compare routing of our  applications with navigating a plane  pilot sets the flight coordinates in our  case route path  and the plane lands on the desired  location or desired page in our app  oftentimes planes carries goods or cargo  and routes carry params info and data  and unfortunately some planes do get  crashed or lost and for out 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 other  to create a component using the cli  enter the following at the command line  where first is the name of your  component  ng generate component first  repeat this step for a second component  but give it a different name here the  new name is second  this guide works with a cli generated  angular application  if you are working manually make sure  that you have base href with slash in  the head of your index.html file  this assumes that the app folder is the  application root and that uses slash  create a new module for routing  name it app  dash routing dot module  define const routes which is type of  routes  here we will define our paths and  components  inside ng module imports array add  router module and call for root module  it routes past as argument  then export your router module so it can  be imported into the root module  at the end define the approaching module  class  import the app routing module into app  module and add it to the imports array  now define your routes in your routes  array  each route in this array is a javascript  object that contains two properties the  first property path 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  assign the anchor tag that you want to  add the route 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 attribute  if you want to style active  link one note the order of routes is  important because the router uses a  first match win strategy when matching  routes so more specific routes should be  placed above  less specific routes often as a user  navigates your application you want to  pass information from one component to  another  to do so you use the activated route  interface  first import router activate a route and  paramap to your component  inject an instance of activated route by  adding it to your application’s  constructor  update the ngoninit method to access the  activator route and track the id  parameter  now we need to adjust our routes to pass  the id param as well  in path add semicolon and name of your  parameter  and then we can add id values to our  links  that’s how you pass and 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 your 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 gonna create two child routes  with the router links of child a and  child b  and give it a second router link  now i’ll create two additional component  with angular cli and name their child a  component  and child b component  a child 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 we 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 with child  can deactivate  resold  and can load  create a service for your guard  ng 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 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 route  configuration  here can activate tells the router to  mediate navigation to this particular  route now if we set the guard to false  we can’t access the route otherwise we  can  and that’s all for routing for this  section  [Music]  after this one we are 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 they’re digital  angular 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 pet class  which defines a data model reflected in  our form  i will have three properties id name and  specie  now let’s import our class in the app  component  define species in species array  now create a model from the pet class  and pass the values for our pet  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 it two divs for  two fields  first will be name input  and i’m adding label  and required attribute to our input  and the second one will be a select  which will loop through an array of  species to show all the values from the  array  same as for input i’m adding label for  select and also i’ll add required  attribute  then i will use ng4 to load through all  the values  and display them  if you run the application right now you  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 path  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 ng model directive declared in the  forms module lets you bind controls in  your template-driven form to properties  in your data model  add the ng-model directive using two-way  data binding syntax  for the name use model dot name  and for species  use model.specie value  when you use ng model on an element you  must define a name attribute for that  element  angular uses the assigned name to  register the element with the ng-form  directive attached to the parent form  element  so in order to register our form add a  template reference variable with a value  of ng form  the pathform template variable is now a  reference to the ng-form directive  instance that governs the form as a  whole  in order to test our application place  the model object in our template with a  json pipe  now if you update your form 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 as form submit event because of  its type submit  to respond to this event take the  following steps  bind the forms ng submit event property  to the pet form component on submit  method  use the template reference variable pet  form 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 button’s 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 violates the required role so it  disables the submit button  to show a response to form submission  you can hide the data entry area and  display something else in its place  wrap the entire form in a div and bind  its 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  shows  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 and  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  [Music]  now in the next section we’re gonna see  how we can take more control of our  forms and how to create reactive forms  [Music]  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 add it to your ng modules  import array  to register a single form control import  the 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  update the template with the 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  where you can listen for changes in the  forms 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 forums have methods to change  the control’s value programmatically  which gives you the flexibility to  update the value without user  interaction  the following example adds a method to  the component class to update the value  of the control to nancy using the set  value  method update the template with a 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 changed  within the component class overriding  its current value  forms typically contain several related  controls reactive forms provide two ways  of grouping multiple related controls  into a single input form  first way a form group defines a form  with a fixed set of controls that you  can manage together and second way a  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 the  constructor with an object of named keys  mapped to their control  for the profile form add two form  control instances with the names first  name  and last name  the individual form controls are now  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 form group  the form group directive listens for the  submit event emitted by the form element  and emits an ng submit event that you  can bind to a callback function  add an ng submit event listener to the  form tag with the on submit callback  method  the onsubmit method captures the current  value of profile form  here we 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 with 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 gonna see how  we can improve our forms  so in this section we are covering form  validation  [Music]  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 i see validation the same as if  you’re at an audition or job interview  something or rather 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 angular runs validation and  generates either a list of validation  errors that results in an invalid status  or null which 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 and mean length  of 4.  i’m binding name input property to ng  model and i’m exporting ngmodel to a  local variable called name  ng model mirrors many of the properties  of its underlying form control instance  so you can use this in template to check  for control states such as valid and  dirty  the ngif of the div element reveals a  set of nested messages divs but only if  the name is invalid and the control is  either dirty or touched  each nested div can present a custom  message for one of the possible  validation errors  these are messages for required and mean  length  now if you type something and leave the  field empty we will get the validation  error message and the same goes if we  enter value less than 4 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 attributes in  template-driven forms such as required  and minland 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  two built-in validators validators  required and validators mean 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 getters at 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 ng model and to bind our name  control to form control name  this form differs from the template  driven version in that it no longer  exports any directives  instead it uses the name getter defined  in the component class  notice that 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 gonna cover  communication using http client  imagine that you’re running a tv station  or a newspaper and what if you lose  communication with your reporters  you would end up with a blank newspaper  or no news to broadcast  oh my god it’s the same thing with web  apps without back-end communication our  apps would be bad without informations  or instructions from the backend  most front-end applications need to  communicate with a server or http  protocol to download or upload data and  access other backend services  before you 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 and 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 getdata method and inside of  this method we’re going to 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 requests 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  and inside of ngoninet method let’s call  our getdata method  because the service method returns an  observable the component subscribes to  the method’s return value  i’m just going to console.log it  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 unfortunately 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 cache error to catch it  i’m gonna lock the error for development  purpose and return throw error with some  message  this should be used in your application  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  applications 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 request for deleting data  from database obviously a put request  which replaces a resource with updated  data now most of the apis require an  authentication key with their requests  so let’s see how we can add that  i found this lordofrings database which  requires an auth key let’s create http  options object with the headers property  this property will be a new http headers  object and we will pass two properties  content type is application json which  means that we are using json as content  and authorization where we enter our api  key barrier is type of authorization and  followed by a key  in order to get your personal key you  need to register link is in the  description box below  now update the api endpoint  and if you try to call without passing  http options you can see that we get an  error  but 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  freecodecamp and if you want to see more  tutorials like this  don’t forget to check out my channel my  name is slovodan and i see you guys in  one of the next videos or tutorials take  care until then  

admin

Leave a Reply

Your email address will not be published. Required fields are marked *