How to Build a Serverless, CMS-powered Angular Application

Angular has taken off in popularity and is in widespread use. Developed and maintained by Google engineers, Angular has found a place all across dynamic web applications and is an increasingly in-demand platform.
Angular offers the advantages of a large and enthusiastic community and outstanding MVC that doesn’t require developers to spend valuable time writing code to put multiple MVC components back together again. In short, Angular is a robust and comprehensive web application framework for front-end development that is unit-testing ready, making it the tool of choice for many developers.
If you’re using Angular, you may run into the need for content management capability — a blog being one example. Adding a CMS to an Angular app may seem daunting, especially if you’re trying to integrate it into a traditional CMS like WordPress, but there’s a new breed of API-based CMS that greatly simplifies things. ButterCMS is one example of a SaaS-based headless CMS that provides a hosted CMS dashboard and content API that you query from your Angular application. This means you don’t need to spin up any new infrastructure to add a CMS to your Angular app.
This tutorial will demonstrate how to build a CMS-powered Angular application that has marketing pages (customer case studies), a blog, and FAQ, all powered via an API. No servers needed!
Installation
First, you’ll get started by installing the Angular CLI.
npm install -g @angular/cli

Set up a new Angular project using Angular CLI. By default, Angular CLI uses CSS styling, so adding the –style=scss flag tells Angular CLI to use SCSS instead:
ng new hello-buttercms-project –style=scss
cd hello-buttercms-project

Install Angular Material and Angular Material related package:
npm install –save @angular/material @angular/cdk
npm install –save @angular/animations

Install ButterCMS. Run this in your command line:
npm install buttercms –save

Butter can also be loaded using a CDN:
<script src=”https://cdnjs.buttercms.com/buttercms-1.1.1.min.js"></script>

Quickly Get Started
Open the project in your code editor of choice. Under src/app create a directory called _services.
We create a file called butterCMS.service.js. This allows us to have your API Token in one place and not accidentally alter it.
import * as Butter from ‘buttercms’;

export const butterService = Butter(‘b60a008584313ed21803780bc9208557b3b49fbb’);

You’ll import this file into any component we want to use ButterCMS.
For a Quickstart, go to src/app/hello-you/hello-you.component.ts and import butterService:
import {butterService} from ‘../_services’;

Inside the HelloYouComponent create methods:
fetchPosts() {
butter.post.list({
page: 1,
page_size: 10
})
.then((res) => {
console.log(‘Content from ButterCMS’)
console.log(res)
})
}

Now call this method when the component is loaded by adding it to the OnInit lifecycle hook:
ngOnInit() {
this.fetchPosts();
}

This API request fetches your blog posts. Your account comes with one example post, which you’ll see in the response.
Next, create another method to retrieve the Homepage Headline Content Field:
fetchHeadline() {
butter.content.retrieve([‘homepage_headline’])
.then((res) => {
console.log(‘Headline from ButterCMS’)
console.log(res)
})
}

Add this method to the OnInit lifecycle hook.
ngOnInit() {
this.fetchPosts();
this.fetchHeadline();
}

This API request fetches homepage headline content. You can set up your own custom content fields to manage any kind of content you need.
Add Marketing Pages
Setting up CMS-powered pages is a simple, three-step process:

Define the Page Type
Create a page
Integrate into your application

Define Page
First, create a Page Type to represent your Customer Case Study pages. Next, define the fields you want for your customer case studies. With your Page Type defined, you can now create the first case study page. Specify the name and URL of the page, and then populate the content of the page.
With your page defined, the ButterCMS API will return it in JSON format like this:
Continue reading %How to Build a Serverless, CMS-powered Angular Application%

Link: https://www.sitepoint.com/how-to-build-a-serverless-cms-powered-angular-application/

How to Update Angular Projects to the Latest Version

In this article, we’ll look at how to update Angular projects to the latest version.
This article is part 6 of the SitePoint Angular 2+ Tutorial on how to create a CRUD App with the Angular CLI.

Part 0 — The Ultimate Angular CLI Reference Guide
Part 1 — Getting our first version of the Todo application up and running
Part 2 — Creating separate components to display a list of todos and a single todo
Part 3 — Update the Todo service to communicate with a REST API
Part 4 — Use Angular router to resolve data
Part 5 — Add authentication to protect private content
Part 6 — How to Update Angular Projects to the latest version.

In part 1 we learned how to get our Todo application up and running and deploy it to GitHub pages. This worked just fine but, unfortunately, the whole app was crammed into a single component.
In part 2 we examined a more modular component architecture and learned how to break this single component into a structured tree of smaller components that are easier to understand, reuse and maintain.
In part 3 we updated our application to communicate with a REST API backend using RxJS and Angular’s HTTP service.
In part 4, we introduced Angular Router and learned how the router updates our application when the browser URL changes and how we can use the router to resolve data from our backend API.
In part 5, we added authentication to our application and learned how we can protect sections from our application from unauthorized access.
Don’t worry! You don’t need to have followed part 1, 2, 3, 4 or 5 of this tutorial for 6 to make sense. You can simply grab a copy of our repo, check out the code from part 5, and use that as a starting point. This is explained in more detail below.
Up and Running
To start on our goal to update Angular, make sure you have the latest version of the Angular CLI installed. If you don’t, you can install it with the following command:
npm install -g @angular/cli@latest

If you need to remove a previous version of the Angular CLI, you can:
npm uninstall -g @angular/cli angular-cli
npm cache clean
npm install -g @angular/cli@latest

After that, you’ll need a copy of the code from part 5. This is available on GitHub. Each article in this series has a corresponding tag in the repository so you can switch back and forth between the different states of the application.
The code that we ended with in part 5 and that we start with in this article is tagged as part-5. The code that we end this article with is tagged as part-6.
You can think of tags like an alias to a specific commit ID. You can switch between them using git checkout. You can read more on that here.
So, to get up and running (with the latest version of the Angular CLI installed) we would do this:
git clone git@github.com:sitepoint-editors/angular-todo-app.git
cd angular-todo-app
git checkout part-5
npm install
ng serve

Then visit http://localhost:4200/. If all’s well, you should see the working Todo app.
Update Angular: Our Plan of Attack
In this article, as we update Angular, we’ll learn the following:

how Angular versions work
where to find instructions on how to update Angular
how to update our code from Angular 4 to Angular 5 (Angular 5 being the latest version at time of writing).

By the end of this article, you’ll understand:

the underlying meaning of specific Angular versions
where to find exact instructions on how to update Angular applications
how to figure out which code changes are required (if any) for Angular 5.

Let’s get started!
The Meaning of Angular Versions
To support a thriving ecosystem, Angular needs to be both stable and evolutionary.
On one hand, Angular aims to provide developers with maximum stability for mission-critical applications. On the other hand, it constantly needs to adapt and advance to support the latest changes in web technologies.
Therefore, the Angular team has decided to use a time-based release cycle with semantic versioning.
A time-based release cycle means that we can expect new versions of Angular (Angular 5, Angular 6, Angular 7, etc.) every couple of weeks or months.
Semantic versioning means that the version number of Angular allows us to predict whether or not it will break our application if we upgrade to it.
In essence, a semantic version looks like this: Major.Minor.Patch.
So version v1.3.8 has a major component with a value of 1, a minor component with a value of 3 and a patch component with a value of 1.
When a new version is released, the new version implicitly indicates the type of change that was made to the code.
The following rules are applied when a semantic version is increased:

Each increment happens numerically with an increment of 1.

When a bug is fixed and the code stays backwards compatible, the patch component is increased:
v0.0.3 // Before bugfix
v0.0.4 // After bugfix

When functionality is added and the code stays backwards compatible, the minor component is increased and the patch component is reset to zero:
v0.2.4 // Before addition of new functionality
v0.3.0 // After addition of new functionality

When a change is implemented that causes the code to become backwards incompatible, also known as a breaking change, the major component is increased and the minor and patch components are reset to zero:
v7.3.5 // Before implementing backwards incompatible changes
v8.0.0 // After implementing backwards incompatible changes

If you’re not familiar with semantic versioning, make sure to check out this simple guide to semantic versioning.
The Angular team combines semantic versioning with a time-based release cycle to aim at:

a new patch release every week
a new minor release every month
a new major release every 6 months

The release schedule is not set in stone, as there may be holidays or special events, but it’s a good indicator of what we can expect in terms of upcoming versions.
You can follow the official Angular blog and the official change log to stay up to date on the latest developments.
A huge benefit of semantic versions is that we can safely update Angular applications with patch or minor releases without having to worry about breaking our applications.
But what if there’s a new major release?
The Angular Update Guide
We already learned that a major release can come with breaking changes. So how do we know if our existing application will break or not if we update it?
One way would be to read the official change log and go through the list of changes.
A much easier way is to use the Angular Update Guide to update Angular. You select your current version of Angular and the version you wish to upgrade to and the application tells you the exact steps you need to take:

For our Angular Todo application, we wish to upgrade from Angular 4.0 to Angular 5.0.
Let’s select app complexity level Advanced so we see all the possible measures we need to take:

We get a complete overview of all the steps we need to take to update our application.
How sweet is that!
Before Updating
The Before Updating list contains 12 items. None of the items apply to our Angular Todo application, so we can safely proceed to the next step.
During the Update
From the During the Update list, only the last item applies to our application. We need to update our dependencies, so let’s run the proposed commands in the root of our project:
$ npm install @angular/{animations,common,compiler,compiler-cli,core,forms,http,platform-browser,platform-browser-dynamic,platform-server,router}@’^5.0.0′ typescript@2.4.2 rxjs@’^5.5.2′

$ npm install typescript@2.4.2 –save-exact

Because we updated our Angular CLI to the latest version in the Up and Running section, we also update our local version:
$ npm install @angular/cli@latest –save-dev

To verify that our application runs correctly, we run:
$ ng serve

If ng serve fails to start, try deleting your node_modules directory and package-lock.json file and run npm install to recreate a clean node_modules directory and package-lock.json file.
Continue reading %How to Update Angular Projects to the Latest Version%

Link: https://www.sitepoint.com/update-angular-projects/

Fun With Angular: A Quick Overview

Angular in the Real World
Angular is one of the more popular JavaScript frameworks in use today. With the backing of a huge company (Google) and the widespread use in the corporate world, it certainly deserves consideration when you are planning your next app development. In this blog post, I’ll take a quick look at the key features of Angular.
Angular was created by Google and was originally released in 2010 as AngularJS – the 1.x version. The initial release of the Angular 2.x version was on September 14, 2016. While the initial release of preview alpha and beta versions existed in 2015, fall 2016 is when we started to see some real traction in its use.

Link: https://dzone.com/articles/fun-with-angular-a-quick-overview?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

Ignite UI for Angular Drawer Menu and Angular Routings

Ignite UI for Angular is a material-based library to speed up the development process of Angular web apps. There are more than 30 components available in Ignite UI for Angular, which help you to write high-performance applications faster. You can learn more about Ignite UI for Angular here.
In this article, we will follow a step-by-step approach to work with Ignite UI Navigation Drawer and Angular Routings. The Ignite UI for Angular Navigation Drawer component is a side navigation container. It can rest on content and slide in/out of view or be pinned to expand/collapse components within the content.

Link: https://dzone.com/articles/ignite-ui-for-angular-drawer-menu-and-angular-rout?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

AngularJS and Angular 2+: a Detailed Comparison

This article compares the major differences between the the original AngularJS and Angular 2+. If you’re currently stuck with an AngularJS project and not sure whether you should make the jump, this article should help you get started.
In recent years, we’ve seen Angular grow tremendously as a framework and as a platform for developing single page applications (SPAs) and progressive web apps (PWAs). AngularJS was built on top of the idea that declarative programming should be used for building the views. This required decoupling the DOM manipulation from the business logic of the application and the approach had many benefits on its own.
However, AngularJS had many shortcoming in terms of performance and how things worked under the hood. Hence, the development team spent a year rewriting the code from scratch and finally released Angular 2 in late 2016. Most developers felt that Angular 2 was a different platform that had very little resemblance to the original AngularJS.
So let’s compare and contrast AngularJS and Angular 2+.
Frameworks in AngularJS and Angular 2
AngularJS follows the traditional MVC architecture that comprises a model, a view and a controller.

Controller: the controller represents how user interactions are handled and binds both the model and the view.
Views: the view represents the presentation layer and the actual UI.
Model: the model is an abstract representation of your data.

Some developers are of the opinion that AngularJS follows MVVM pattern that replaces the Controller with a View-Model. A View-Model is a JavaScript function that’s similar to that of the controller. What makes it special is that it synchronizes the data between a view and a model. The changes made to a UI element automatically propagate to the model and vice versa.
The following diagram shows how various AngularJS pieces are connected together.

You can read more about AngularJS’s architecture on the official documentation page.
Angular, on the other, hand has a component-based architecture. Every Angular application has at least one component known as the root component. Each component has an associated class that’s responsible for handling the business logic and a template that represents the view layer. Multiple, closely related components can be stacked together to create a module and each module forms a functional unit on its own.

As you can see in the figure, the component is bound to the template. Components are composed using TypeScript classes and templates are attached to them using @Component annotations. Services can be injected into a component using Angular’s dependency injection subsystem. The concept of modules in Angular is drastically different from that of the AngularJS modules. An NgModule is a container for defining a functional unit. An NgModule can comprise components, services and other functions. The modular unit can then be imported and used with other modules.
All the Angular concepts are better explained at Angular.io.
Templates in AngularJS and Angular 2
In AngularJS the template is written using HTML. To make it dynamic, you can add AngularJS-specific code such as attributes, markups, filters and form controls. In addition, it supports the two-way data binding technique mentioned earlier. The following code snippet demonstrates the use of directives and double curly brackets within the template:

<!– Body tag augmented with ngController directive –>
<body ng-controller=”MyController">
<inpu#t ng-model="foo" value="bar">
<!– Button tag with ngClick directive –>
<!– Curly bracket is a template binding syntax –>
button ng-click="changeFoo()"></button>
<script src="angular.js"></script>
</body>
</html>

In Angular, AngularJS’s template structure was reworked and lots of new features were added to the templates. The primary difference was that each component had a template attached to it. All the HTML elements except <html>, <body>, <base>, and <script> work within the template. Apart from that, there are features such as template binding, template interpolation, template statements, property binding, event binding and two-way binding. Built-in attribute directives like NgClass, NgStyle and NgModel and built-in structural directives such as NgIf, NgForOf, NgSwitch are also part of the template.
Continue reading %AngularJS and Angular 2+: a Detailed Comparison%

Link: https://www.sitepoint.com/angularjs-vs-angular/

Hybrid Spring Boot and React or Angular: A Better Way

This article presents a better solution for a hybrid React or Angular and Spring Boot project. It uses create-react-app or ng new and overlays a Spring Boot Maven project on top, which is the inverse of other approaches. The goal is to retain a first-class React or Angular dev environment alongside Spring Boot and attempt to find a no-comprises approach for both.
If you want to see the solution, please jump ahead in this article. All source code is available at https://github.com/murphye/hybrid-react-angular-spring-boot-apps

Link: https://dzone.com/articles/hybrid-spring-boot-and-react-or-angular-a-better-w?utm_medium=feed&utm_source=feedpress.me&utm_campaign=Feed%3A+dzone%2Fwebdev

Webinar Recap: Learning Advanced Angular Component Concepts [Video]

I hosted a webinar on Advanced Angular Component Concepts on the 19th of January. This webinar covered: Content Projection ViewChild and ViewChildren ContentChild and ContentChildren Dynamic Component Creation For your benefit, we went ahead and wrote articles on the topics covered in the webinar. You can read them in the blogs linked above.

Link: https://dzone.com/articles/webinar-recap-learning-advanced-angular-component

Angular Testing: A Developer’s Introduction

In this guide, we’ll look at how we can write automated tests in Angular 5 projects. Angular Testing is a core feature available in every project that was set up with either the Angular CLI or the Angular quick start project.
The subject of Angular testing is vast, as it’s a complex and very involved topic. It would require several chapters or a full-length course to cover it fully. So in this guide, I’ll show you just the basics to get you started.
Prerequisites
At the time of writing, Angular 5.2 is the current stable version — which is what we’ll be using here. This guide assumes you at least have a solid grasp of Angular 4+ fundamentals. It’s also assumed you at least understand the concept or have some skills writing automated tests.
We’ll base our testing examples on Angular’s official beginner tutorial to demonstrate how to write tests for components and services. You can find the completed code with tests on our GitHub repository. At the end of this guide, you should have the skills to implement several passing tests in Angular 5.

Angular Testing Technologies
As you already know, an Angular project is made up of templates, components, services and modules. They all run inside what’s known as the Angular environment. While it’s possible to write isolated tests, you won’t really know how your code will interact with other elements within the Angular environment.
Luckily, we have several technologies that can help us write such unit tests with the least amount of effort.
1. Angular Testing Utilities
This is a set of classes and functions that are needed to build a test environment for Angular code. You can find them on Angular’s api documentation. The most important of all is the TestBed. It’s used to configure an Angular module just the same way as the @NgModule — except that it prepares the module for testing. It has a configureTestingModule function where you provide all the necessary dependencies for your component to function in a test environment. Here’s an example of the dashboard component being prepared to run in a test environment. Several dependencies are needed by this component for the test to run:
TestBed.configureTestingModule({
imports: [ RouterTestingModule ],
declarations: [ DashboardComponent ],
schemas: [ NO_ERRORS_SCHEMA ],
providers: [
{
provide: HeroService,
useClass: MockHeroService
}
],
})
.compileComponents();

We’ll look more closely at what’s going on here a little further below.
2. Jasmine
Jasmine is the de facto framework for writing Angular tests. Basically, it’s a testing framework that uses the behavior-driven notation. Writing a test in Jasmine is quite simple:
describe(‘createCustomer’ () => {

it(‘should create new customer’,(customer) => {

expect(response).toEqual(newCustomer)
});

it(‘should not create customer with missing fields’, () => {

expect(response.error.message).toEqual(‘missing parameters’)
});

it(‘should not create customer with existing record’, () => {

expect(response.error.message).toEqual(‘record already exists’)
});
});

The anatomy of a Jasmine test is made up of at least two elements: a describe function, which is a suite of tests, and an it function, which is the test itself. We normally use describe to indicate the function we’re focusing on — for example, createCustomer(). Then, within the suite, we create multiple it tests. Each test puts the target function under a different condition in order to ensure it behaves as expected. You can refer to the Jasmine docs for more information.
3. Karma
Karma is a tool for executing source code against test code inside a browser environment. It supports the running of tests in each browser it’s configured for. Results are displayed on both the command line and on the browser for the developer to inspect which tests have passed or failed. Karma also watches the files and can trigger a test rerun whenever a file changes. At the root of the Angular project, we have the file karma.conf that’s used to configure Karma. The contents should look something like this:
module.exports = function (config) {
config.set({
basePath: ”,
frameworks: [‘jasmine’, ‘@angular/cli’],
plugins: [
require(‘karma-jasmine’),
require(‘karma-chrome-launcher’),
require(‘karma-jasmine-html-reporter’),
require(‘karma-coverage-istanbul-reporter’),
require(‘@angular/cli/plugins/karma’)
],
client:{
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
reports: [ ‘html’, ‘lcovonly’ ],
fixWebpackSourcePaths: true
},
angularCli: {
environment: ‘dev’
},
reporters: [‘progress’, ‘kjhtml’],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: [‘Chrome’],
singleRun: false
});
};

Do check out Karma’s configuration documentation to learn how to customize it. As you can see, Chrome is listed as the browser to use for running tests. You’ll need to define an environment variable called CHROME_BIN that points to the location of your Chrome browser executable. If you’re using Linux, just add this line to your .bashrc file:
export CHROME_BIN=”/usr/bin/chromium-browser"

In order for Karma to run your tests, you must ensure the test files end with .spec.ts. You should note that Karma was designed to mostly run unit tests. To run end-to-end tests, we’ll need another tool, Protractor, which we’ll look into next.
4. Protractor
Protractor is an end-to-end test framework for Angular. It runs your tests inside a real browser, interacting with it as real person would. Unlike unit tests, where we test individual functions, here we test the entire logic. Protractor is able to fill in forms, click buttons and confirm that the expected data and styling is displayed in the HTML document. Just like Karma, Protractor has its own configuration file at the root of your Angular project, protractor.conf:
const { SpecReporter } = require(‘jasmine-spec-reporter’);

exports.config = {
allScriptsTimeout: 11000,
specs: [
‘./e2e/**/*.e2e-spec.ts’
],
capabilities: {
‘browserName’: ‘chrome’
},
directConnect: true,
baseUrl: ‘http://localhost:4200/’,
framework: ‘jasmine’,
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000,
print: function() {}
},
onPrepare() {
require(‘ts-node’).register({
project: ‘e2e/tsconfig.e2e.json’
});
jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
}
};

You can find the documentation for its configuration here. Unlike Jasmine/Karma tests, Protractor tests are located outside the src folder, in a folder called e2e. We’ll look into writing end-to-end tests later down the road. For now, let’s start writing unit tests.
Continue reading %Angular Testing: A Developer’s Introduction%

Link: https://www.sitepoint.com/angular-testing-introduction/