Skip to main content

Angular 1.5 - Stateless components

Angular 1.5 brings us ‘Components’, a special kind of directive that uses a simpler configuration. It is a first step towards Angular 2.0 where directives and controllers no longer exist and are replaced by a component-based model.

Advantages and disadvantages of components

From the Angular documentation:

Advantages of Components:

  • simpler configuration than plain directives
  • promote sane defaults and best practices
  • optimized for component-based architecture
  • writing component directives will make it easier to upgrade to Angular 2

When not to use Components:

  • for directives that rely on DOM manipulation, adding event listeners etc, because the compile and link functions are unavailable
  • when you need advanced directive definition options like priority, terminal, multi-element
  • when you want a directive that is triggered by an attribute or CSS class, rather than an element

Most important to remember is that components have their own isolated state(meaning that only isolated scope is supported) and that no DOM interactions are possible.

An example

I created a small ‘PreviousNext directive’ that enable/disable previous/next buttons in a wizard. This directive uses state on a higher level wizardcontroller.

Here is the original code:

"use strict";
(function (app) {
app.directive('previousNext', function () {
return {
restrict: 'AE',
replace: 'true',
template: '<div class="span4"><button type="button" ng-disabled="currentStep===0" ng-click="previous()" class="btn btn-default">Previous</button><button type="button" ng-click="next()"class="btn btn-default">{{isLastStep()?"Complete":"Next"}}</button></div>'
};
});
}(angular.module("wizardApp")));
<previous-next></previous-next>
view raw view.html hosted with ❤ by GitHub
"use strict";
(function (app) {
var wizardController = function ($scope, $window) {
$scope.steps = ['Step 1', 'Step 2', 'Step 3'];
$scope.currentStep = 0;
$scope.isBusy = true;
$scope.getCurrentStep = function () {
return $scope.steps[$scope.currentStep];
};
$scope.next = function () {
if ($scope.isLastStep()) {
//Removed code
} else {
$scope.currentStep++;
}
};
$scope.previous = function () {
$scope.currentStep--;
};
$scope.isLastStep = function () {
return $scope.currentStep + 1 === $scope.steps.length;
};
};
wizardController.$inject = ["$scope","$window"];
app.controller("wizardController", wizardController);
}(angular.module("wizardApp")));

I decided to rewrite this directive to a component but to keep things simple I left most of the state in the wizardcontroller.

Here is the code rewritten as a component:

"use strict";
(function (app) {
app.component('previousNext', {
template: '<div class="span4"><button type="button" ng-disabled="$ctrl.currentStep===0" ng-click="$ctrl.onPrevious()" class="btn btn-default">Previous</button><button type="button" ng-click="$ctrl.onNext()"class="btn btn-default">{{$ctrl.isLastStep()?"Complete":"Next"}}</button></div>',
bindings: {
onPrevious: '&',
onNext: '&',
isLastStep: '&',
currentStep:'<'
}
});
}(angular.module("authorizationScopeWizardApp")));
<previous-next current-step="currentStep" on-previous="previous()" on-next="next()" is-last-step="isLastStep()"></previous-next>
view raw view.html hosted with ❤ by GitHub

Let’s have a look at the main differences:

  • We didn’t specify a controller meaning that Angular creates one for us behind the scenes. It also creates a controllerAs value for us, $ctrl by default. So the $ctrl calls inside the template are calling a generated controller available through the $ctrl alias.
  • We used bindings to control the inputs and outputs of our component. Inputs are bound with the ‘<’  symbol and indicates a one-way binding. Output are bound with the ‘&’ symbol and function as callbacks to events. So we read out the currentStep value, call onNext, onPrevious and isLastStep functions on our generated controller that are routed to functions on the parent  (wizard)controller.

I could further improve this component by moving all the previous/next logic inside the component and call a function to feed the currentStep back to the wizardController. But this is an exercise I leave up to the reader… Smile

Popular posts from this blog

Kubernetes–Limit your environmental impact

Reducing the carbon footprint and CO2 emission of our (cloud) workloads, is a responsibility of all of us. If you are running a Kubernetes cluster, have a look at Kube-Green . kube-green is a simple Kubernetes operator that automatically shuts down (some of) your pods when you don't need them. A single pod produces about 11 Kg CO2eq per year( here the calculation). Reason enough to give it a try! Installing kube-green in your cluster The easiest way to install the operator in your cluster is through kubectl. We first need to install a cert-manager: kubectl apply -f https://github.com/cert-manager/cert-manager/releases/download/v1.14.5/cert-manager.yaml Remark: Wait a minute before you continue as it can take some time before the cert-manager is up & running inside your cluster. Now we can install the kube-green operator: kubectl apply -f https://github.com/kube-green/kube-green/releases/latest/download/kube-green.yaml Now in the namespace where we want t...

Azure DevOps/ GitHub emoji

I’m really bad at remembering emoji’s. So here is cheat sheet with all emoji’s that can be used in tools that support the github emoji markdown markup: All credits go to rcaviers who created this list.

.NET 9 - Goodbye sln!

Although the csproj file evolved and simplified a lot over time, the Visual Studio solution file (.sln) remained an ugly file format full of magic GUIDs. With the latest .NET 9 SDK(9.0.200), we finally got an alternative; a new XML-based solution file(.slnx) got introduced in preview. So say goodbye to this ugly sln file: And meet his better looking slnx brother instead: To use this feature we first have to enable it: Go to Tools -> Options -> Environment -> Preview Features Check the checkbox next to Use Solution File Persistence Model Now we can migrate an existing sln file to slnx using the following command: dotnet sln migrate AICalculator.sln .slnx file D:\Projects\Test\AICalculator\AICalculator.slnx generated. Or create a new Visual Studio solution using the slnx format: dotnet new sln --format slnx The template "Solution File" was created successfully. The new format is not yet recognized by VSCode but it does work in Jetbr...