Styling components in Angular 2

In my last post I went through creating a few simple components. In this post I’m going to play around with styling in those components …

Adding styles and using ngClass

First, I’m going to change the results so that we see all the customers highlighting the matches. So, it will look something like this …

SearchComponent needs to change to …

  • On line 21 we are now initialising a status property on each customer
  • On Lines 23 to 30 we have an updateCustomers() method which sets the status property on a customer to highlight if matched

ResultsComponent needs to change to …

  • We now have a highlight style name defined on line 10
  • On line 18 we use the ngClass directive to set the class on the span to the customer’s status property

Encapsulation

I’m now going to play around to see whether the style leaks out of the component.

First, lets reference the style in the parent component, SearchComponent …


… and we see that the style doesn’t leak up – “Search for a company” doesn’t have a yellow background …

Now let’s add a child component to ResultSubComponent to see if the style leaks down. ResultsComponent is now …

… and the code for ResultSubComponent is …


On line 6 we reference the highlight class.
If we run the app we see that the style doesn’t leak down – “is this text highlighted?” doesn’t have a yellow background.

This is great – generally, this is what we want. However, what if we do want the styles to leak down into sub components? We can make use of the ViewEncapsulation enum on the encapsulation property in the search component …

Line 2 sets the encapsulation to “Native” which means the shadow DOM is used. The result is what we want – the styles leak down into the sub components …

However, although this works in Chrome, it doesn’t work in Firefox, IE or Edge because they don’t support shadow DOM yet.

Here are all the encapsulation modes …

  • None. No encapsulation – the styles will leak up and down
  • Native. Shadow DOM encapsulation – the styles will leak down, but this only works in Chrome at the moment
  • Emulated. The default encapsulation – the styles do not leak out
Connect with me:RSSGitHubTwitterLinkedIn

Building a simple component in Angular 2

A while back, I posted about building a simple component in react. In this post, I’m going to go through building that same component in Angular 2 …

The component will look like below. There will be a parent component with 2 child components …

  • Criteria. The search textbox and “go” button
  • Results. The list of results
  • Search. The overall component – the parent of Criteria and Results

Consuming component

The code of the consuming component is listed below …

  • On line 2, we import the search component which is our top level component
  • On line 6, we declare that we are going to use the search component in the component’s markup
  • Finally on 8, we reference the search component, using it’s tag which will be search

Search component

The code for the search component is listed below …

  • Lines 3 and 4 import the criteria and results components
  • Line 8 declares that the criteria and results components are going to be referenced in the markup
  • Line 11 references the criteria component and calls the handleSearch() function when the critieria’s update event occurs
  • handleSearch() is declared on lines 33 to 37. The implementation finds the customers matching the given criteria and sets the filteredCustomers property
  • Line 12 references the results component and sets its data property to the search component’s filteredCustomers property. The data property will be updated every time the filteredCustomers property is updated automatically by angular

Criteria component

The code for the criteria component is listed below …

  • There is an update custom event declared on line 14. The search component makes use of this to trigger a search
  • Line 8 calls the handleClick() method, passing the value of the criteria, which in turn triggers the update event

Results component

The code for the results component is listed below …

  • On line 17 we have a custom property declared called data which the search component uses to pass in the data
  • Lines 9 to 11 make use of angular’s ngFor to iterate over the data and display the name for each item

That’s it – pretty simple!

Connect with me:RSSGitHubTwitterLinkedIn

Angular 2 Custom Events

In my last post I covered passing data into components via custom properties. In this post I’ll deal with passing data out of components via custom events …

Let’s say we want to implement a component to capture a name, telephone number and email address. Our component code initially looks like this …

However, want to expose a save event so that the consumer of this component can do something with the captured name, telephone number and email address. We want to reference the component like this …

So, we need to expose a custom event called save.
Here’s how we do this …

We declare save as a property in our ContactComponent class on line 16.
We need to prefix the property with the Output annotation. This tells angular that this is a property that can output data. We need to import the Output annotation on line 1.
The type of the property is an EventEmitter. More info on EventEmitter can be found in the angular docs.
On line 21, we trigger the next save event, passing the name, telephone number and email address to the consumer.

So, we can now consume the component as follows …


… which results in the name, telephone number and email address being output to the console when the save button is clicked.

Connect with me:RSSGitHubTwitterLinkedIn

Passing Data to Sub Components in Angular 2

Let’s say we have a list of products we need to display and we want a sub component to be responsible for displaying each product. We want it to look something like this …
sub component

Parent component

So, our parent component is as follows to begin with …

… Line 8 iterates through the products and line 9 is ready to reference a sub component.

Sub component

Our sub component is as follows …


Lines 9 and 11 reference a product object that, at the moment, the sub component isn’t wired up to …

Wiring them up

First we need to reference the sub component from the parent component by adding an import statement …


… and also referencing the selector in the template.

However, we need to pass the product when we call the sub component. First we need to use the Input annotation in the sub component to declare that a property called product can be passed in …


In the parent component, we can then set the product property when we reference the sub component.

That’s it – nice an simple!
Here’s the full listing of the parent and sub components …

Connect with me:RSSGitHubTwitterLinkedIn

Angular 2 Async Validation

I recently posted about Angular 2 Form validation which didn’t cover asynchronous validation. This post does cover an async validation example …

I’ve put all the classes in the same file to make the example simpler to show and read. The example gives a textbox for the user to enter a product code and validates that the product code exists and puts a description at the side if it does.

Referencing an async validator in FormBuilder

The first key point is that you reference the async validator in the 3rd parameter in FormBuilder.group(). None async validators go in the 2nd parameter – I only have a async validator in my example.

Writing the async validator

The async validator needs to return a promise that in turn returns null if valid or something else if not valid. In this example, I am calling a ProductService class to check whether the product exists

Here’s the full listing …

Connect with me:RSSGitHubTwitterLinkedIn

8 Reasons to use TypeScript

I’ve been using TypeScript again whilst using Angular 2. I dismissed TypeScript a few years ago because the tooling surrounding it was a bit too painful and I didn’t think it would gain traction. Things have improved a lot. Here’s why I think it is worth considering using TypeScript – particularly when writing decent sized web apps …

1. Readability

The TypeScript syntax is really nice – I find it easier to read than the equivalent JavaScript. This can have a significant impact on the maintenance cost with large codebases with large teams. Here’s some sample TypeScript on the left and the equivalent JavaScript on the right:

You can see that the TypeScript is much cleaner – no IFFE to mimic a class or “prototype” references when defining functions, …

2. ES6 in older browsers

TypeScript lets you use ES6 features today in older browsers because TypeScript can compile to ES5. Features like classes in the above example, arrow functions in the example allow you to write cleaner code …

3. IntelliSense

IntelliSense allows you to understand APIs quicker. Again this can improve productivity in large codebases.

4. Familiar Object Oriented style

The TypeScript syntax is very similar C# and Java. So, if you have a lot of experience in these languages, you will be right at home with TypeScript.

5. Catch errors quicker

TypeScript can catch errors as you write your code. A common mistake I make with JavaScript is typing out the wrong property or function name when consuming an API. Without TypeScript, these errors are caught when you run the code or when you write a unit test. With TypeScript, these errors are caught as you type the incorrect code. Again, this improves productivity.

6. Not all or nothing

The migration to TypeScript can be gradual – you don’t have to migrate every line of code from JavaScript to TypeScript before releasing. You can migrate the short, simple files that are referenced a lot first, to start gaining a good level of benefit. You don’t have to migrate all areas of code to TypeScript as well – there are cases when strong typing adds a lot of friction.

7. Traction

Looking at Google Trends, TypeScript has continued to gain traction in the last couple of years since release. Angular 2’s dependency on TypeScript will mean that traction will continue to grow – Angular is hugely popular.

8. Mature

TypeScript was released to the general public towards the end of 2012 after 2 years of internal development at Microsoft.
So, there’s been lots of development following feedback in the last couple of years. The tooling surrounding TypeScript is now much better and WebStorm and Visual Studio Code now give excellent experiences now when writing TypeScript code.

Connect with me:RSSGitHubTwitterLinkedIn

Angular 2 Two Way Binding

In my last 2 posts I went through the event binding and property binding syntax in Angular 2. Event binding flows from the component’s template to the model and property binding flows in the opposite direction from the model to the template.

Event and property binding are one-way binding. Two-way binding is where the data flows in both directions between the component’s template and model. Given that event binding uses () syntax and property binding uses [] syntax it makes sense 2 way binding uses [()] syntax!

Angular 2 binding

The ngModel directive allows us to do 2 way data binding. In the following example the criteria component property is bound to the search input’s value in both directions …

Connect with me:RSSGitHubTwitterLinkedIn