Angular Data Binding Basics

Draft Ready

Angular Data Binding BasicsDEFAULT HEADER TEXT

This time we are going to tackle Angular Data Binding Basics. Data binding is a powerful, and helpful tool that can save you a lot of coding. Binding data is easy in Angular, and we are confident that by the time you finish reading this article, you will have a good feel for how to apply it to your projects.
For the examples in this post, we are going to use a new project created with the Angular CLI. If you are not familiar with the Angular CLI or you’re starting a new project, we recommend our article that tackles those problems: Angular CLI For Beginners – Your first Angular Application.
Once you have the new project created, have the CLI start the project, and open it in your browser.

Getting Started

Let’s get started with some Angular data binding basics.

Start the Angular CLI

Begin by typing ng serve into the command prompt from within the my-first-angular-application directory. Starting the CLI should allow you to see the Angular Welcome page in your browser. We are going to try our Angular data binding basics on this page.

Data Binding

There are two types of data binding: one-way, and two-way.

One-Way Data Binding

As the name suggests, one-way data binding allows you to bind data in one direction only. You can either pass data to the DOM from the component or, you can pass data from the component to the DOM.

There are three ways to accomplish one-way data binding with Angular. You can bind the data using interpolation, property binding, or event binding. We’ll give you a few examples of each type of these data binding basics to help you get a better feel for how they work.

Interpolation

Interpolation is an example of a component to DOM data binding. It uses matching double curly braces in your HTML markup like these {{ }}. Between the double curly braces, you use a JavaScript expression that Angular can evaluate and convert to a string.

Example 1 – Literal

To try out interpolation, navigate to your app.componen.html file. On line 352 of that file, you should see some markup that looks like Example 1A.

Example 1A

https://gist.github.com/kevinchisholm/d76c1e714812c6dc4cf9f7713c3508d2

Let’s add the double curly braces and a simple expression, so it looks like Example 1B.

Example 1B

https://gist.github.com/kevinchisholm/e0b9970c6ee2da06a47dea514dd38de5

Once you make the changes and save the file, you can see the change in the browser. You should see Resources 4.

Some expressions are not supported, like assignments and incrementing/decrementing, and you can only have one expression.

Example 2 – Property

Interpolation usually displays a class property we set somewhere else. Navigate to the app.component.ts file and add the line name = ‘my-first-angular-application’, as seen in Example 2A. We are adding the property name to the class AppComponent.

Example 2A

https://gist.github.com/kevinchisholm/e05bfdef384b41f9a24082c8911a315e

Once you complete the changes and save the app.component.ts file, you can navigate back to the app.component.html file and add the name property between the curly brackets instead of the statement, as seen in Example 2B.

Example 2B

https://gist.github.com/kevinchisholm/03c73e3c0d2613461ba94af6bb74dae9

Save the app.component.html file, and you can see in your browser that Angular is displaying the property that you have set.

Now that you know what you are looking at, you can see another example of this a few lines earlier in the app.component.html file at line 344 as seen is example 2C.

Example 2C

https://gist.github.com/kevinchisholm/79301916e54d1da99e6f920398f4b2e2

This line of code is telling Angular to display another property of AppComponent called title, and you can look once again at the app.component.ts file (Example 2A) to see this property inside the AppComponent class.

Example 3 – Method

You can also use interpolation to call methods. If you navigate back to the app.component.ts file, you can add the method myMethod(), as seen in Example 3A.

Example 3A

https://gist.github.com/kevinchisholm/841833a8f76e4b535f9f2010290867e0

Then, in the app.coomponent.ts file, you can use the double curly braces to call the method, as seen in Example 3B.

Example 3B

https://gist.github.com/kevinchisholm/243f4954dfaac85329ad08d8d1673084

Property Binding

Another way to approach Angular data binding basics is to use property binding. Property binding is another example of a component to DOM data binding, and it allows Angular to use the HTML elements DOM properties. The syntax for Angular property binding is to put the HTML DOM property in square brackets and set it equal to the class property inside the HTML tag like this:  <h1 [DOMproperty] = classproperty></h>.

Example 4

In Example 4, we are going to use the DOM property textContent to display the name property we created. Check out the code in Example 4A.

Example 4A

https://gist.github.com/kevinchisholm/8667ae875e511bf1e37d6a59ef629203

If you run this code and check your browser, you will see that you end up with the same result that you did with interpolation in Example 2B.

We can also use property binding call methods. In Example 4B, we replace the name property with the myMethod method and get the same results in our browser that we get with Example 3B.

Example 4B

https://gist.github.com/kevinchisholm/42353e196a50fd91bd3b96758866ce21

We can also write the same thing another way. We can remove the square brackets around the DOM property and put the class property in the interpolation double curly brackets, as you can see in Example 4C. Checking the browser, you will see the same result.

Example 4C

https://gist.github.com/kevinchisholm/eca06aea96f606483d2a6826d64b7eed

Event Binding

One example of DOM to component data binding in Angular is Event Binding. Event binding in Angular allows you to set up event handlers inside your components. We can use events to call methods from within our components by placing the event inside parentheses and setting it equal to the method in quotes inside an HTML tag like this: <h1 (event) = “method”></h1>.

Example 5

We’ll try this idea by using the click event on the H1 tag we have been using. Navigate to the app.component.ts page first and add the myEvent method to the component, as we see in Example 5A.

Example 5A

https://gist.github.com/kevinchisholm/b6df6efe3da73c4928f5654671f109b0

Then, navigate to the app.component.html page, add the click event to the H1 element, and set it equal to your myEvent method, as you see in Example 5B.

Example 5B

https://gist.github.com/kevinchisholm/d31882153cdffbef9c058493b7035406

After you have added this code and saved your work, navigate to the browser and open the JavaScript console. Each time you click on the word “Resources,” Angular will call the myEvent method, which will print “Click!” to the console window.

You can see several more examples of real-world event binding if you scroll down past line 389 of the app.component.html. These examples look like Example 5C.

Example 5C

https://gist.github.com/kevinchisholm/0aab6974c5ade9ae9115b8bee7e57521

Two-Way Data Binding

Two-way data binding allows the component to exchange data with the DOM, and it also allows the DOM to exchange data with the component. You can accomplish two-way binding easily by using the ngModel directive in Angular. The syntax looks like this: [(ngModel)]=”someVariable”.

You can try out two-way binding yourself by adding the code in Example 6 to your project.

Example 6

https://gist.github.com/kevinchisholm/0b73e4bab16cf009cdefea00d20344f3

In this code, we can see that the ngModel is inside an input element and is set equal to myMessage. In the next line, We use interpolation to print the value of myMessage to the screen.

If you check your browser, you will see that you can now type into an input box, and the message will appear as you type. We think you‘ll agree that ngModel is a reasonably painless way to add two-way data binding.

Another important thing about the code in Example 6 is that if you look closely, you’ll notice the square brackets, parentheses, and the double curly brackets we used when we were talking about one-way data binding. The similarity is because what’s really happening here, is that we are using two one-way data bindings at once, and ngModel is taking care of the work behind the scenes.

You can create custom two-way data bindings in Angular that don’t use ngModel, but that’s outside the scope of this article.

Conclusion

Our hope is that you can see how data binding is a powerful asset provided by Angular, and we have just barely scratched the surface of what is possible. There are dozens of DOM methods at your disposal, besides the textComment that we use in this Angular data binding basics guide, and you are not limited to built-in elements like the H1 tag. You can create new elements and use them the same way. There are plenty of other events besides the click that can trigger calls to methods within your components, and you can create two-way bindings that are a bit more complex, but every bit as powerful as ngModel.

If you have learned something new and enjoyed reading over these examples, please share this guide to Angular data binding basics on Facebook and Twitter.

Create a New Angular Component

Draft Ready

create a new Angular componentDEFAULT HEADER TEXT

Angular is a component-based framework, and we are going to show you how to create a new Angular component within that framework. An Angular application will contain one or more components, and each has a specific task. We begin with one main component called the parent, and all others are child components of that parent. A child can also contain and parent other child components.

It might be easiest to compare Angular components to an automobile, wherein the car is the main parent component, and the door, headlight, carburetor, and fuel pump are all child components. A car door also contains window controls and an opening mechanism, which are child components of the door component. Components are similar to classes.

Create a New Angular Component

Let’s take a look at what you’ll need to do to create a new Angular component.

Start a New Project

When creating an application, or website with the Angular CLI, the first thing you’ll need to do is create a new Angular component, which is what we’re going to go over right now. We’re going to start with a new project created by the Angular CLI. If you’re not sure how to start a new project with the Angular CLI, we recommend going over our article Angular CLI For Beginners – Your first Angular Application, then come back here to continue.

With the new project created, we can move into that directory with the command cd my-first-angular-application and run the command ng serve to see our application in the browser. If you look at the page now, you’ll notice that it’s a nice looking website for the Angular framework. It provides some examples, as well as links to get more information.

Understand the Parent Component

When we created our new project using the Angular CLI, the CLI created the parent component for us. The name of the component is AppComponent, and it can be found in the file app.component.ts and should look like Example 1.

Example 1

https://gist.github.com/kevinchisholm/7deab755ab350a625253d2201d785b8b

This is what that file is saying:

  • Import a new empty component from the Angular core.
  • Name the component AppComponent, and give it one property called title.
  • Set the property title to equal my-first-angular-application.
  • The component will do what it does when it sees the tag app-root.
  • What it does will be contained in the file app.component.html.
  • Any styling that is required by this component is in the file app.component.css.

If we navigate to the main index.html file and look at the code, it should look like Example 2.

Example 2

https://gist.github.com/kevinchisholm/8b186020f06f024237924667ef98a371

If we look at the code on this page, we’ll see the tag app-root that we said would tell the component to do what it does. The tag uses an HTML element, and a matching closing HTML element must also be present. Since the app-root is the only tag in the body of the HTML page, we can safely assume the component is responsible for creating the entire page. The working component is even more evident if we change the file to look like Example 3.

Example 3

https://gist.github.com/kevinchisholm/34afc2b03af39359c8b2ad6628ed33d4

Once we change the page to look like Example 3, we can see the angular component is indeed creating all of the HTML for this website.
It’s also interesting to note that the component does not hold up the rest of the HTML on a page. If you were to refresh your browser page, you would notice that the Angular component takes a little bit longer to load than the rest, but the “End” text we placed in the code still shows up before the component. If the component held up the HTML, the “End” text wouldn’t show up until after the component was loaded. We’re going to delete the extra code we used in Example 3, though, because we don’t need it.

Since we have shown that the component is responsible for creating the web page, we should be able to find the code for the page in the app.component.html file. If we navigate to the app.component.html file, we can see that it does contain the code for the website. I’m not going to post it here because it’s a large file. One thing that is interesting to notice about this file, though, is that the CSS is included with the HTML and should be in the app.component.css file in a real project.

Register the Component as an Angular Module

One more thing that we need to discuss that applies to all components, including the parent, is the need to register them as an angular module in the app.module.ts file. If you look at the code in the app.module.ts file, you should see something that looks very much like Example 4.

Example 4

https://gist.github.com/kevinchisholm/bc1aee0b8daf76eee4f491ec52830e9c

The important thing to notice about this file is that we’re importing the AppComponent component. Declare it as an Angular module and make it the bootstrap, which means it’s the main component that starts the Angular application.

Delete the Boilerplate Website

There may be times when you want to modify the boilerplate page, and there are plenty of excellent examples in the code that we might use in the future, to help demonstrate an idea, but for the most part, you’re going to want to start with a blank page and build your application from there.

To remove the boilerplate website, navigate to the app.component.html file, and delete all of the code in that file. Once you have done that and save the file, you should only see a white page in your browser.

Create a New Component File

In Angular, each component gets its own file, so the first thing we need to do is create a component file. The convention for naming these files is, name dot component dot ts. You can see, for example, the main component AppComponent is in a file named app.component.ts.

We’ll call our component MyFirstComponent, so we’ll put it in a file called my-first.component.ts. The easiest way to create the file is to copy the app.component.ts file and rename it so that you can modify the code within, to create a new component. Go ahead and create that file now, and place it in the same directory as the app.component.ts file.

You’ll need to modify the code inside so it looks like Example 5.

Example 5

https://gist.github.com/kevinchisholm/ea71f023de08fefd135c64fd02f55f2e

As you can see, this new component looks very much like the main parent component, as all of your components will.

  • Every component will need to import the basic component frame from the Angular core.
  • Every component will need a name. In this case, the name is MyFirstComponent.
  • Every component can have as many properties as it requires. In this case, we have no properties set yet, except the parent component AppComponent, which has one property called title.
  • Every component will require a unique selector, which in this case, is app-first-child.
  • Every component will require an HTML file to hold its working code, and the CSS file to decorate that code.

You are not required to follow the naming convention for the HTML file or the CSS files, nor are you required to keep them in the same directory. As long as you have it labeled correctly in the component and the path to the file is correct, it will work. You can also put the code for either in as a literal, bypassing the need for external files, but we recommend using external files to keep the code clean, and using the naming convention so that you remain consistent across all of your applications.

If you haven’t done so already, you’ll need to create the empty HTML and CSS files we named in the component now, and place them in the same directory as the my-first.component.ts file.

Register the New Component as a Module

Just as the parent component needs to be registered, child components will also need to be registered as modules. Registration is how angular knows that your component is part of the application.

To register your module, navigate to the app.module.ts file, and change the code to look like Example 6.

Example 6

https://gist.github.com/kevinchisholm/0f5f1abe4e5d27ea43ed47b592edccdb

In Example 6, you can see that we’ve imported our new component, and included it in the module declarations. Once we’ve declared our component as a module, we are finished.

Test the Components

Now that the new Angular component is complete, we can add some code so that we can see it in action.

Test AppComponent

First, let’s test the parent component AppComponent by adding some code to the app.component.html file. Update your file to add the line of code in Example 7.

Example 7

https://gist.github.com/kevinchisholm/12afb5f52bf64b0ba306be983cbd9c2b

If you check your browser after adding this code, you will see that it now correctly displays our message, showing us that the AppComponent is still working.

Test MyFirstComponent

To see our new component in action, first, navigate to the my-first.component.html file and add the line of code seen in Example 8.

Example 8

https://gist.github.com/kevinchisholm/c7c65166de26d682e51f8b43004a4693

If you check your browser now, you will not see anything new. The reason that nothing is changed is that we need to have our parent component call our new child component, using the selector we have chosen: app-first-child.

Navigate to the app.component.html file and update the code to look like Example 9.

Example 9

https://gist.github.com/kevinchisholm/b5ec2e36b4b318e912eeebceb923c8f1

You can see in Example 9, that we have used our selector app-first-child inside of an HTML element to call our child component from inside the parent component. If you check your browser now, you will see that our new component is displayed.

Worthy of Note

The parent component can only be called once, as we can see if we update our index.html file to look like Example 10. Angular will only respond to the first call.

Example 10

https://gist.github.com/kevinchisholm/5810be4ee1ac324fa6f32d6622cfe018

The child component can be called an unlimited amount of times, as we can see if we update our app.component.html file to look like Example 11.

Example 11

https://gist.github.com/kevinchisholm/8d3dd7554a33e6751032df8be4ef79a0

The child component can only be called by the parent component, as we can see if we update our index.html file to look like Example 12.

Example 12

https://gist.github.com/kevinchisholm/cdffc6e306aaa182d36908c793a9e5a4

Conclusion

As you can see, it’s not very difficult to create a new Angular component, and creating a second, third, or 100th component will follow the same steps. Components keep our code modular and reusable. They also make it much easier to understand later after you’ve been away from the code.

For many of the guides to using Angular CLI that we have created, you begin here, with a new, empty component that can be used for trying out examples. If you are going to move on to our more advanced guides, we recommend saving this project so you can use it as a starting point.

We hope you’ve enjoyed reading this guide on how to create a new Angular component, and have learned something new. If so, please be sure to share it on Facebook and Twitter.

Securely Reference secrets in serverless.yml – Keeping Sensitive Data Out of Your Code

Draft Ready

securely reference secrets in serverless.ymlSooner or later, your application will need access to a secret that you need to hide from others. AWS Systems Manager Parameter Store provides a way to securely reference secrets in serverless.yml

If you leverage the serverless framework to manage and deploy your cloud application, then you are well aware of the elegance and power of serverless.yml. The ability to configure your entire service in version managed code is invaluable. As soon as your service matures in complexity, however, you will likely need to leverage a secret value. The challenge is: how do you keep that secret safely hidden, yet access it in your serverless.yml file? Fortunately, the AWS Systems Manager Parameter Store has a way of letting you securely reference secrets in serverless.yml.

Securely Reference Secrets in serverless.yml Using the AWS Systems Manager Parameter Store

AWS Systems Manager Parameter Store provides a way to securely store and reference secrets such as passwords, API keys or database connection scripts. While this AWS service has a bit of a long and awkward name, it is easy to implement. If you plan to follow along with the code examples in this article, you’ll want to create a new parameter in the AWS Systems Manager Parameter Store.

How to Set Your Secret in AWS Systems Manager Parameter Store

  • Go to https://console.aws.amazon.com/systems-manager/parameters
  • Click the Create parameter button
  • Where it says Name, enter a name for your parameter (for this article, I used: “myApiKey”)
  • Where it says Type, select SecureString
  • Where it says Value, enter the value. This is your secret (for this article, I used: “foo-bar-baz”)
  • Click the Create parameter button

Example 1

https://gist.github.com/kevinchisholm/e2f2bf019758f9a8734c2f75a84d941d

In Example 1, we have a very simple service that exposes an endpoint via a lambda. Most of what you see is standard for creating a simple serverless. The line to note is # 11. Here we set an environment variable named myApiKey. Note the syntax: ssm:/myApiKey~true. This tells the serverless framework to access a parameter named myApiKey from AWS Systems Manager Parameter Store and the ~true portion of that code indicates that it is a SecureString.

Example 2

https://gist.github.com/kevinchisholm/5d3fac37d855a2f402ad75e832596bc6

In Example 2, we have the code for our lambda function. This function returns JSON in its HTTP response. In that JSON, we have the text Decrypted Secret: ${process.env.myApiKey}. This means that we should see the value of the myApiKey environment variable, which was retrieved from AWS Systems Manager Parameter Store and has the value: “foo-bar-baz”.

Example 3

https://gist.github.com/kevinchisholm/d6597dd0d09dbc0ed1cb90df2f3eaa90

In Example 3, we see the JSON that is returned in the browser when we hit our endpoint.

Summary

The AWS Systems Manager Parameter Store provides a simple yet reliable way to securely reference secrets in serverless.yml. The end result is that you have access to important secrets such as passwords, API keys or database connection scripts, while hiding those secrets from anyone who is not authorized to view them.

In this article, we saw that it’s not difficult to securely reference secrets in serverless.yml, thereby keeping sensitive data out of your code. We hope that you have enjoyed reading about this valuable capability and that you’ve learned something new. If you have and it has made your coding easier and more efficient, please share this article on Facebook and Twitter.

Angular @input and @output Basics

Draft Ready

Angular @input and @output basicsDEFAULT HEADER TEXT

In this post, we are going to be taking a look at some Angular @input and @output basics to help you get a better understanding of how these commands work. A standard Angular application has many components that can nest inside each other. When one component is inside another component, we call the outer component the parent. The inner component is the child. Angular uses the @Input decorator to send data from the parent to the child, and the @Output decorator sends data from the child to the parent.

We are going to take a close look at both to see how they work and we are going to be using the Angular CLI so we can see the results of our efforts in real-time. We also begin with a new project in the CLI because it’s the easiest way for us all to start with the same code and get the same results.

If you are not familiar with the Angular CLI and you’re setting up a new project, we recommend checking out our Angular CLI – Getting Started and Angular CLI for Beginners to get up to speed.

Getting Started

Once you have the Angular CLI running and you can see the application in the browser, we can begin to work on the Angular @Input and @Output basics.

In Angular, you create components and add properties to those components. You make those properties available to child components with the Angular binding syntax decorator called @Input. An Angular decorator allows you to modify a class without changing the source code. Decorators are functions that enable a directive, service, or filter modifications. Decorators always have an @ symbol before their names — for example, @Component, @Input, and @Output.

Create a New Component

The first thing we need to do is create a new component to try our code on. This component will be the child, that will receive data from the parent, already created for us by the Angular CLI and named AppComponent. The AppComponent is in the app.component.ts file.

To create a new component for Angular, create a new file in the src/app/ folder called test-item.components.ts. You will also need to create the test-item.components.html and test-item.components.ts files in the same folder.

We cover creating a new component in another article, so to keep it simple, copy the code in Example 1 to your test-item.components.ts file and save it.

Example 1

https://gist.github.com/kevinchisholm/a5c60e749dad16f6eece5ae54da37b54

We will also copy the contents of Example 2 into our test-item.components.html file.

Example 2

https://gist.github.com/kevinchisholm/b8935d8e37a9fb9577f923e4814b30a8

Once you have these two files created and saved, we need to navigate to the app.module.ts file and change the code so it will import our child component TestItemComponent. Change the code in the app.module.ts file to look like Example 3.

Example 3

https://gist.github.com/kevinchisholm/ac9f5737e3d632931772d14905a65755

The final step in creating a child component is to navigate to the app.component.html file and add a DOM element named my-test-component. We are going to add the DOM element at line 351 for this example, and when finished, it should look like Example 4.

Example 4

https://gist.github.com/kevinchisholm/3e5595339a8c2f3022ebc672b156af6b

If everything went correctly, you should see the HTML from our new child component displayed near the top of the page in our CLI. If you didn’t understand what was going on while we were creating this component, we recommend checking out our Creating a New Component in Angular to learn more about it.

  • When we run our application, the parent component AppComponent calls the child component TestItemComponent, which displays the HTML data contained within that component.

In this example, we only call the child component once, but most applications might call a child component several times, and each time, it may be required to display different data. To do that, we would need the parent component to send the new data to the child component, and that is where the @Input decorator comes in to play.

@Input

First, we’ll take a look at the @Import decorator

Import the Input Decorator

Now that we have added a new child component, we can start to work on Angular @Input and @Output basics. Let’s get started by importing the @Input decorator.

  • Before we can use the @Input decorator, we need to import it from the Angular core package.
  • We will import the @Input decorator on the test-item.component.ts page.

It’s easy to import the @Input decorator because we already use another decorator on this component called @Component, and that decorator also requires importing from the Angular core package, so the import statement is already in place. We only need to add Import to the statement.

To import both the component and input decorators from the Angular core package, modify your test-item.component.ts file, so the first line looks like Example 5.

Example 5

https://gist.github.com/kevinchisholm/d937c9f5b95571e43abfe61a6c31ecd5

Create a Class Property

We use @Input decorators on class properties because the property is what holds the data.

The next thing we will do is create a class property called testProperty and add it to our TestItemComponent class, as seen in Example 6.

Example 6

https://gist.github.com/kevinchisholm/225643cbf89a3dd8c3918852a03c446a

Add the Input Decorator

With the @Input decorator imported, we can use it on our new property. To make use of it, add the @input decorator to our testProperty, as seen in Example 7.

Example 7

https://gist.github.com/kevinchisholm/0469ae9d683df85315ba0339b58fc724

The @Input decorator tells Angular to support any bindings placed on any instances of the my-test-item element where the property name is testProperty.

Using the Input Decorator

To use the Input decorator, navigate to the app.components.ts page where we will create an object literal that contains data we can use. We will call the object sampleData, and the code should look like Example 8 when you are finished.

Example 8

https://gist.github.com/kevinchisholm/1aa8e670d36ad1b340498361aacdb254

  • Notice that the new object sampleData which contains the new data is inside our parent component AppComponent.
  • We changed the data slightly from the test-item.components.html file so you can be sure the Input decorator is working correctly.

Bind the Data

To send the data in our sampleData object to the my-test-item HTML element, we navigate back to line 351 of our app.component.html file, and we change it to look like Example 9.

Example 9

https://gist.github.com/kevinchisholm/020a639ae4d1e09cce8f8f437aa2d6d5

In Example 9, we bind the sampleData object to the testProperty property in our TestItemComponent class. This binding is taking place inside the HTML of the parent component AppComponent and is binding the data to a property of the child TestItemComponent. Our child component can now check its testProperty property to get the new data.

Use the Data

Once the sample data is bound to our child component, we can use it by navigating to the test-item-component.html file and changing the code to look like it does in Example 10.

Example 10

https://gist.github.com/kevinchisholm/4ac77bf19a12814ba08b7b4bcb8e8cbc

Once you have saved the file, if you look at the page in the browser, you can see that the TestItemComponent child class does have access to the sample data in the parent class.

@Output

Now that we have seen how to use the @Input decorator to allow a parent to communicate with the child component, let’s take a look at the @Output decorator, which enables the child to communicate with the parent component. Components can emit events in Angular using the @Output decorator, along with an Event Emitter.

Import the Output Decorator

The first thing we need to do to use the @Output decorator is to import it from the Angular core as we did with the @Input decorator. To do this, change the first line in your test-item.components.ts to look like Example 11.

Example 11

https://gist.github.com/kevinchisholm/e53dae15b521610f18e69b6b81b5b7cb

Adding the Output Decorator

We will also need to create a new property in the TestItemComponent and link it to the @Output decorator line as we did with the @Input. This time we’ll call the property in our child component delete, and you should update your code to look like example 12.

Example 12

https://gist.github.com/kevinchisholm/c21f8257e539c20cdb356298dd8bbb25

Add an Event Emitter

Output decorators work with event emitters, and you need to import them as well. Event emitters are part of the core package, so we can import them the same way we did with the others. Update the first line of your test-item,components.ts file to look like Example 13.

Example 13

https://gist.github.com/kevinchisholm/4da3dbe2068747f46b7fbe04d2d6a731

Once you have imported the event emitter, we want to set our testDelete property to a new event emitter, as we see in Example 14.

Example 14

https://gist.github.com/kevinchisholm/05d1fdcc5443a2a7a5c36fb71f5ff987

Emitting the Event

To emit an event, an action needs to take place. Assuming a click event triggers a call to an onDelete method, we will emit the output event in that method. Adjust the code in your test-item.components.ts file to look like Example 15.

Example 15

https://gist.github.com/kevinchisholm/161e42a508eca03561743bb4dd5cc67b

We have set the delete property to be an emitter, and emitters have a built-in method called emit, so we can use this.delete.emit. This method expects to return a value, which can be null, but in this case, we set it to return this.testProperty, which refers to the data we are deleting.

Use the Event

Once you have changed the code to look like Example 15, the @Output emitter in our child component is ready, and it’s time to make use of it. You need to navigate back to line 351 of the app.component.html file and change the code to look like Example 16.

Example 16

https://gist.github.com/kevinchisholm/7c068c1c3d98f5ca94913d02e41aa23f

In this example, we are binding the event in the child component to a statement called onTestPropertyDelete. Since the onDelete method returns testProperty, we can access that value using $event. So, when the my-test-item emits the delete event, we call the onTestPropertyDelete method, which exposes the data for deletion in the parent component.

All that is left is to add the onTestPropertyDelete method to our app.component.ts file. To add the method, navigate to the app.component.ts file, and change the code, so it looks like Example 17.

Example 17

https://gist.github.com/kevinchisholm/473342e6396c2613240cc15326caafe4

The onTestPropertyDelete method is in the parent component, and this is where you would place your code to handle deleting the text.
When the click event occurs, the child component sends the required data to the parent component, which does the deleting.

Conclusion

So, in closing, we hope that our discussion of Angular @Input and @Output basics has helped you get a better handle of the advantageous features of the Angular framework, and that you understand a little bit more about the communication between child components and parent components. These tools will allow your web pages and applications to be far more versatile and interactive, without adding a lot of extra code.

With the @Input decorator, you can format and present large amounts of information such as phone books or recipe books, with simple and readable code. The @Output decorator works with events such as clicks, hovers, on-load, etc. to create an extremely dynamic experience. We hope you will keep reading as we explore more ways to use Angular to develop better applications. If you have enjoyed our guide to Angular @Input and @Output basics, please share it to Facebook and Twitter.

Programmatically Create Amazon Cognito Groups – Amazon Cognito As a Service

Draft Ready

programmatically create Amazon Cognito GroupsImplementing Amazon Cognito As a Service is a smart way to define your user pool in version managed code. It is likely that you’ll want to leverage groups in your user pool, which means you need to programmatically create Amazon Cognito Groups in your serverless.yml file.

If you are reading this, you have likely implemented Amazon Cognito As a Service using the serverless framework. For this article, I will assume that you have read my earlier post: Amazon Cognito As a Service – Setting Up Your serverless.yml File. If you have not read that article, you might want to review it before proceeding to programmatically create Amazon Cognito Groups.

Why Programmatically Create Amazon Cognito Groups?

User groups are not at all a requirement of Amazon Cognito. That said, it is a very useful feature and one that most will likely want to implement. Implementing Amazon Cognito As a Service is a great start but why do that, only to go into the AWS Console and start clicking around?? The XXX as a service approach means never having to manually change settings in the AWS console (or as close to never as possible, but in most cases, never is very much possible).

https://gist.github.com/kevinchisholm/8892cdef8c996ae10cd1afd4003c1fb0

Using the serverless.yml file from the previous post: Amazon Cognito As a Service – Setting Up Your serverless.yml File, we have already done the work of configuring our Cognito user pool.

On line 25, we start to programmatically create Amazon Cognito Groups. There are three user groups defined here: admins, editors, and authors. These group names have absolutely no inherent meaning; they are arbitrary and for demonstration purposes only. The reason I have specified three groups is that I wanted to point out that you can provision multiple groups and show how the properties are all very similar.

Let’s focus on lines 26-32. Here we have created the admins group. At this point, you are probably getting used to looking at serverless.yml files, so I won’t go through every single property here. Just note that for each group, we specify a description (e.g. line 29) and a name (e.g. line 30). The rest of the properties for the group should be self-explanatory. And of course, for the editors and authors groups, only the description and name fields will differ.

Deploying Your Amazon Cognito Service

In order to see the changes in our Amazon Cognito service we need to take the following steps:

  • Open your terminal application
  • Move into the same folder as your serverless.yml File
  • Run the command: sls deploy -s dev (If you omit the “-s” flag, the default value of “dev” will be used)
  • Go to console.aws.amazon.com/cognito
  • Click the icon for your user pool
  • Click Users and Groups, and then click the Groups tab
  • You will see your user groups defined

Summary

In this article, we covered the steps needed to programmatically create Amazon Cognito Groups in your serverless.yml file. You do not need to leverage groups in your user pool, but if you plan to use them, it just makes perfect sense to have these group definitions version managed. This means that you’ll want to programmatically create Amazon Cognito Groups in your serverless.yml file. Moving towards a 100% serverless methodology for your application is in most cases a smart way to go.

We hope that you have enjoyed reading about how to programmatically create Amazon Cognito Groups and have learned something new. If you have and it has made your coding easier and more efficient, please share this article on Facebook and Twitter.

Create a Custom Domain Name For Your AWS Lambda Using the serverless-domain-manager Plugin

Draft Ready

create a custom domain name for your aws lambdaThe HTTP endpoints that AWS generates are cryptic and arbitrary. If you create a custom domain name for your aws lambda, you can have an endpoint that is more attractive to developers and easier to manage.

In this article, I will explain how to create a custom domain name for your aws lambda. I use the serverless framework to manage and deploy my AWS services. This article assumes that you do the same.

When you deploy your AWS Lambda, you will see some information on the CLI, assuming your deployment was a success. One of these blocks of information is “endpoints”. AWS generates your HTTP URLs automatically for you. This is great (I’m serious when I say that). And for most scenarios, that is enough. But what about when you want to share your endpoint with the world? Be it developers or customers, api.mydomain.com/orders is much easier to remember or manage than d8tce1pthd.execute-api.us-east-1.amazonaws.com/dev/orders.

The serverless-domain-manager NPM module is a serverless framework plugin that makes it easy to create a custom domain name for your aws lambda. There is a two-step process. Step 1 is to create your custom domain. Step 2 is to deploy your service. Before we dive into those steps, let’s go over the prerequisites and review the code examples.

Prerequisites

Serverless framework

If you plan to follow along with the code examples, you will need to install the serverless framework.

Domain Registration and SSL certificate

In order to create a custom domain name for your aws lambda, you need to have that domain registered with AWS. Once you have that domain registered with AWS, you will need an SSL certificate for that domain. Below are a few links that provide helpful information on these topics:

https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/registrar.html

https://docs.aws.amazon.com/acm/latest/userguide/gs-acm-request-public.html

Also, this video is helpful:

Getting a free SSL certificate with AWS Certificate Manager for CloudFront (AWS howto)

(you can probably stop at 3:20)

Example 1 – package.json

https://gist.github.com/kevinchisholm/8d59ffd7e605b9806c8c342ecdb7f4e9

In Example # 1, we have the package.json file for our code. Not too much to discuss here. Just note that the serverless-domain-manager plugin is a dev dependency.

Example 2 – serverless.yml

https://gist.github.com/kevinchisholm/d1799ce76bcf5a5d22b50652415af11e

In Example # 2, we have the serverless.yml file for our code. On line # 3, we have added the serverless-domain-manager plugin to the plugins section. On line # 12, we have added a custom.customDomain section. Let’s take a closer look at each property:

  • basePath – allows us to define what each lambda’s path builds upon. For example, if our base path is “orders” then our endpoints might look something like this: api.foo.com/orders/hats, api.foo.com/orders/shoes, api.foo.com/orders/shirts, etc.
  • createRoute53Record – Tells AWS to create an A Alias and AAAA Alias records in Route53.
  • stage – The stage to create the domain name for.
  • domainName – The domain name to be created in API Gateway and Route53 (if enabled) for this service.
  • certificateName – The name of a specific certificate from Certificate Manager to use with this service.
  • certificateArn – The arn of a specific certificate from Certificate Manager to use with this API.

Example 3 – The Lambda Function

https://gist.github.com/kevinchisholm/4533a38af8662d19fa463f0936a9d965

In Example # 3, we have our AWS Lambda file. I this case, we have two functions defined in our serverless.yml file, but we reference two module.exports properties in the same file. This was done to keep the code examples as simple as possible.

Both of the functions exported here are very simple: they return JSON that indicates which function they belong to.

Deploying Your Service

Use the serverless-domain-manager NPM module to create the sub-domain (one-time step)

  • Move into the root of your project folder
  • Run the command: serverless create_domain -s dev
  • Wait 20-40 minutes for the sub-domain to be created

Deploy your project

  • Move into the root of your project folder
  • Run the command: npm install
  • Run the command: sls deploy -s dev

View your endpoints

  • Visit the endpoint https://XXX.YOUR-DOMAIN.com/orders/hats
  • Visit the endpoint https://XXX.YOUR-DOMAIN.com/orders/shoes
  • You should see the appropriate messages in the browser.

NOTE: replace XXX.YOUR-DOMAIN.com with your actual custom domain

Export Your Amazon Cognito User Pool – Amazon Cognito As a Service

Draft Ready

export your Amazon Cognito user poolIf you have implemented Amazon Cognito As a Service, chances are you may develop other services that depend on it. The best way to manage this kind of dependency is to export your Amazon Cognito user pool.

For this article, I am going to assume that you have already read my post: Amazon Cognito As a Service – Setting Up Your serverless.yml File. If you have not read this article, you might want to review it before proceeding. The reason for this suggestion is that it’s not difficult to export your Amazon Cognito user pool, but you’ll want to do so in the same serverless.yml file in which you define your Cognito user pool.

Why Export your Amazon Cognito User Pool?

It is not at all required that you export your Amazon Cognito user pool. In fact, it is perfectly acceptable that you might create many Amazon Cognito user pools and never have a need to export them. When considering if you need to export yours, however, the question that needs to be asked is: does one or more of my other services depend on my Cognito user pool? If the answer is “no,” then there is nothing further needed. If the answer is “yes”, then read on.

How to Export Your Amazon Cognito User Pool

Example # 1

https://gist.github.com/kevinchisholm/88bd7a3ea504010b3890c61aea777aed

In the above code example, we have all the steps needed in order to export your Amazon Cognito user pool. I won’t take up time reviewing lines 1-25. If you have any questions about what is happening there, I suggest you review my previous article: Amazon Cognito As a Service – Setting Up Your serverless.yml File.

Starting on line 27, we have the steps needed to export your Amazon Cognito user pool. In the Outputs section, we export two things: the ID of the user pool, and the ID of the user pool client. Notice that this Outputs section is a property of resources.Resources.

And finally, for both outputs, in order to consume them in any services that need them, look at the Export property. The value that’s set tells you how to reference the output. So for example, if you want to consume the value of Outputs.UserPoolId, you would reference: UserPoolId-my-user-pool-dev or UserPoolId-my-user-pool-prod, etc. And if you want to consume the value of Outputs.UserPoolClientId, you would reference: UserPoolClientId-my-user-pool-dev or UserPoolClientId-my-user-pool-prod, etc.

How to Consume Your Exported Amazon Cognito User Pool

Example # 2

https://gist.github.com/kevinchisholm/ef594a2814974e3d81a0985f3e63d7cc

In Example # 2, we have a very simple service that sets two environment variables: UserPoolId and UserPoolClientId. In both cases, we use the !ImportValue syntax to get the value of the property that was exported from our User Pool Service.

Summary

In this article we saw that it’s not difficult to export your Amazon Cognito user pool; you just need to do so in the same serverless.yml file in which you define your Cognito user pool. We hope that you have enjoyed reading about this service and that you’ve learned something new. If you have and it has made your coding easier and more efficient, please share this article on Facebook and Twitter.

Implement If Then Logic In serverless.yml – How To Conditionally Set Serverless Framework Properties

Draft Ready

implement if then logic in serverless.ymlThe serverless.yml file is a powerful tool that allows for dynamic property values. But what about the need to implement if then logic in serverless.yml? The serverless-plugin-ifelse npm module saves the day.

How to Implement If Then Logic in serverless.yml

The serverless-plugin-ifelse npm module is a life-saver. It allows you to implement if then logic in serverless.yml and conditionally determine which portions of that file are set or excluded. In this article, I will walk through a few basic examples that demonstrate how to implement if then logic in serverless.yml.

The serverless framework alleviates virtually all of the pain associated with provisioning AWS CloudFormation stacks. One of the most well thought out aspects of this framework is serverless.yml. This file provides a straightforward way to configure your CloudFormation stack in code. It also supports dynamic properties (e.g. “stage”). But it will not be long before you find yourself wishing to include or exclude certain portions of your serverless.yml file, or set specific values based on a dynamic context such as stage. This is when it pays to know how to implement if then logic in serverless.yml.

Example 1 – package.json

https://gist.github.com/kevinchisholm/265e28c5f2b23e1db673b9eb6dc1ef4c

In Example # 1, we have the package.json file needed by our service. We set the serverless-plugin-ifelse npm module as a dependency, so just be aware that you will need to run the command npm install in the root of your service folder before deploying your service.

Example 2 – Exclude and ElseExclude

https://gist.github.com/kevinchisholm/38ba7fe30ed2a0238f6d1e018b8a9a3e

In Example # 2, we have leveraged the Exclude and ElseExclude features of the serverless-plugin-ifelse npm module in order to implement if then logic in serverless.yml. Let’s dig into the details:

  • We have two functions: fooFunction and barFunction.
  • If the stage IS “prod” when we deploy, then exclude fooFunction
  • If the stage is NOT “prod” when we deploy, then exclude barFunction

The end result is: you will wind up with two functions deployed.

Here are the endpoints you should see:

  • https://XXX.execute-api.us-east-1.amazonaws.com/dev/foo
  • https://XXX.execute-api.us-east-1.amazonaws.com/prod/bar

Example 3 – Set and ElseSet

For Examples 3-A, 3-B and 3-C we will have one function. That function shows a message. The message is a combination of a static value and a dynamic value. The dynamic value is determined by our stage when we deploy. In this example, we will use Set and ElseSet in order to implement if then logic in serverless.yml.

Example 3-A

https://gist.github.com/kevinchisholm/65d6566a4d01d3971b0a367c0b899538

In Example 3-A we have our serverless.yml file. Starting on line 15, here is the logic:

  • If the stage IS “prod” when we deploy, the dynamicMessage value is: “this is a dynamic PROD message”
  • If the stage is NOT “prod” when we deploy, the dynamicMessage value is: “this is a dynamic DEV/TEST message”

Example 3-B

https://gist.github.com/kevinchisholm/45347779e2ee0572595234bdabc13390

In Example 3-B we have our lambda. This handler returns an HTTP response and the message property is a combination of the staticMessage and the dynamicMessage.

Example 3-C

https://gist.github.com/kevinchisholm/0f49c52632e6bf3ffd325d26e0d1ff24

In Example 3-C we have two messages that you see in the browser, depending on which endpoint you hit. As expected, the dynamic message differs, based on the deployment stage.

Summary

One of the biggest challenges of serverless.yml is that it is not a context that supports programming logic. The serverless-plugin-ifelse npm module provides a way to implement if then logic in serverless.yml. This provides a great deal of power with regard to dynamically including, excluding or setting values based on the deployment stage.

In this article, we saw that it’s not difficult to implement if then logic in serverless.yml, thereby conditionally setting serverless framework properties. We hope that you have enjoyed reading about this valuable capability and that you’ve learned something new. If you have and it has made your coding easier and more efficient, please share this article on Facebook and Twitter.