Archive for May, 2017

May 29th, 2017
1:18 pm
CouchDB View emitting the same document twice

Posted under CouchDB
Tags , , ,

I had a bug whereby my view was emitting the same place document twice. This was strange as the database clearly did not contain 2 copies of the document. I had seen what appeared to be a similar issue before bud at the time did not track down the cause.

It turned out to be a bug in the view definition. The original (buggy) version follows:-

function (doc) {
  if (doc.type == ‘place’) {
      emit([doc.address.postTown, doc.address.locality, doc.name, doc._id, 0], null);
      emit([doc.address.postTown, doc.address.locality, doc.name, doc._id, 1], {_id: doc.placeFeaturesId});
  }
}

The problem with this is that when doc.placeFeaturesId is null/undefined, the second emit emits its key plus an “_id” with an undefined/null value in the generated json. The result of this is that when using ?include_docs=true to include the documents, CouchDB applies a default behaviour due to the null, and emits the place document again a second time. The following fix prevents the second emit when there are no placeFeatures present, which prevents the place document being emitted a second time. This solves the problem:-

function (doc) {
  if (doc.type == ‘place’) {
      emit([doc.address.postTown, doc.address.locality, doc.name, doc._id, 0], null);
      if (doc.placeFeaturesId) {
        emit([doc.address.postTown, doc.address.locality, doc.name, doc._id, 1], {_id: doc.placeFeaturesId});
      }
  }
}

The lesson here is to be careful to handle undefined or null values in the view code when emitting entries in a view definition as this can cause strange behaviour such as the duplicates above.

No Comments »

May 26th, 2017
12:55 pm
Dynamically updating css classes on child components from a parent property

Posted under Angular & CSS & PrimeNG
Tags , , ,

I was using a button component to encapsulate the primeNG one, to allow it to responsively change to an icon only button at smaller screen widths. Whilst in theory I could have dynamically modified the internal primeNG button CSS, this was complex and I did not want  to become tightly coupled to it. My button component therefore simply selected one of 2 buttons via a media query, setting the unwanted one to display:none.

I wanted any classes added to the top level ss-button to be set on the underlying primeNG buttons. One use of these buttons was in a home brewed tab component, and  I was dynamically changing the button colour via ui-button-primary, ui-button-secondary so that the active tab had a ‘primary’ coloured button and the inactive ones were ‘secondary’ which caused them to become uncoloured ghost buttons – ideal for my requirement.

During refactoring to replace the ‘full size only’ primeNG buttons with the resizing ss-buttons I introduced a bug and the colour change failed to work. The initial (incorrect) refactored code was as follows:-

ss-tab-toolbar.component.html

<ng-container *ngFor="let tab of tabs">
<app-ss-button [label]="tab.label" [icon]="tab.icon" (click)="setActiveTab(tab)"
[ngClass]="{'ui-button-primary': isActiveTab(tab), 'ui-button-secondary': ! isActiveTab(tab)}"></app-ss-button>
</ng-container>

ss-button.component.html

<button pButton type="button" [title]="label" [label]="label" [icon]="icon" class="ss-button icon-text"
[ngClass]="class" ></button>
<button pButton type="button" [title]="label" [icon]="icon" class="ss-button icon-only"
[ngClass]="class" ></button>

ss-button.component.ts

@Component({
selector: 'app-ss-button',
templateUrl: './ss-button.component.html',
styleUrls: ['./ss-button.component.scss']
})
export class SSTabButtonComponent {

@Input() label: string;
@Input() icon: string;
@Input() class: string;

constructor() { }
}

The issue was that I was using [ngClass] dynamically to update the classes on the <app-ss-button> in ss-tab-toolbar.component. html. This used to work for the PrimeNG buttons, but now would have no effect as the classes need to be changed on the child buttons not the encapsulating parent. A simple change of [ngClass] to [class] fixed the problem, as the parent style change then updated the property on the parent component which was then picked up by the children correctly.

modified ss-tab-toolbar.component.html

<ng-container *ngFor="let tab of tabs">
<app-ss-button [label]="tab.label" [icon]="tab.icon" (click)="setActiveTab(tab)"
[class]="{'ui-button-primary': isActiveTab(tab), 'ui-button-secondary': ! isActiveTab(tab)}"></app-ss-button>
</ng-container>

Happily the dynamic nature of angular meant that this worked perfectly for tab changes – the change on the parent class was propagated correctly to the child and the button colours changed correctly.

I was wondering initially whether I would need to involve observables to make this work but this was not the case – this kind of dynamic propagation pattern is worth remembering in future.

No Comments »

May 18th, 2017
6:30 pm
Tricks with the PrimeNG Grid CSS Component

Posted under Angular & CSS & HTML & PrimeNG
Tags ,

Update 19/5/2017

I noticed that my original attempt below, whilst causing the text div to flow under the image div at smaller screen sizes, did not cause the text div to be full width when it was sitting underneath. To do this properly I needed to use a combination of 2 specific non-default (i.e. not ui-g-*) responsive style classes on the text div, in this case ui-md-9 and ui-sm-12. This causes the following:-

  1. At the u-md-* screen size boundary, and higher, the ui-md-9 kicks in and the image and text are on the same line.
  2. Below the ui-md-9 boundary, the ui-sm-12 kicks in and allows the text div to be full width. Without this, it would sit underneath but the default ui-g-9 would still be in effect so it would not switch to full width.

The modified code fragment for the item-text div is as follows:-

<div class="ui-g-9 ui-sm-12 ui-md-9 item-text">

Original Post

I did this quite by accident, due to adding an unwanted “>” on the end of a ui-g-3 class for the div around the left image in a data list – it caused the class to be ignored.

The code (with the offending character and the ui-g-3 class removed) is as follows:-

<ng-template let-place pTemplate="item">
<div class="ui-g list-item item-image">
<div class="item-image">
<img src={{place.thumbUrl}}>
</div>
<div class="ui-g-9 item-text">
<h4>{{place.shortLocation}}</h4>
<h3>{{place.name}}</h3>
<p>{{place.strapline}}</p>
</div>
</div>
</ng-template>

The scss for the component is here (note this is from the component scss file so is encapsulated by Angular from bleeding out):-

h3 {
font-size:1.1em;
font-weight: normal;
margin:.2em 0;
}
h4 {
font-size:1em;
font-weight: normal;
margin: 0;
}
p {
font-size:1em;
margin:.2em 0;
}
.list-item {
padding:.5em;
border-bottom:1px solid #D5D5D5;
display:flex;
align-items: center;
}
.list-item .item-image {
padding-right:1em;
}
.list-item .item-text {
padding-left:0;
}

The happy effect of this was that the image div did not have a ui-g-* class to size it, so had a fixed size determined by the thumbnail, and was not a floating div. When I used a ui-g-3 class for it by removing the offending “>”, then the gap between the image and the text increased as the width changed, which is not something I wanted – the fixed padding there due to the bug was fine for all screen widths.

The ui-g-9 class happily floated next to it and flowed underneath as required. Different ui-g-* classes such as ui-g-6 and ui-g-8 just caused the flow to happen at a different width point.

I could probably have achieved a similar effect by using a ui-g-3 class for the image as I had intended, and then explicitly fixing the width for that div (or e.g. setting a min-width and a max-width).

I may need to do this or re-jig it if I have to cater for different thumbnail sizes, but my preferences is to scale all thumbnails to the same size as it gives a much better layout.

Whether this trick technically breaks or violates the ui-g-* grid css rules I am not sure, the documentation on them is not hugely comprehensive, but I will ponder this one in due course.

For now it works fine!

No Comments »

May 18th, 2017
5:56 pm
Vertically Centering items in a div–2017 version!

Posted under Angular & CSS & PrimeNG & Web
Tags ,

I posted about this kind of issue back in 2010 here.

Nowadays for my own project work I am happy to assume recent browsers, in particularly IE11 at least (noting that even this has been out a while now – it was released 4 years ago now so a reasonable start point).

This means that I am happy to use css Flex which makes this insanely simple compared to the old days. You just need display:flex;align-items:center in the container div and its content items will centre vertically.

I’ve just used this on a PrimeNG data list component to centre left thumbnails correctly in a list item with no issues.

Quite why we have had to suffer for so many years with arcane tricks (or risk ridicule by making it simple using tables for layout) is beyond me, but there we are.

No Comments »

May 18th, 2017
11:22 am
Webstorm IDE–Oragnising Imports Tips/Gotchas

Posted under TypeScript & WebStorm
Tags ,

1/ Organising imports does not seem to happen automatically when it should. To organise imports for a given folder or the project, select the appropriate level in the navigator then hit Code/Optimise Imports or ctrl+alt+0 as detailed here.

2/ TSLint gives errors about double quotes in imports as it prefers single quotes in all the code (double quotes for html), but Webstorm uses double quotes by default when organising imports. You can change Webstorm to use single quotes as per this post here.

No Comments »

May 15th, 2017
4:07 pm
Angular–using parent component references

Posted under Angular & TypeScript
Tags ,

I had a need to do this initially when implementing my own tab container component.

I wanted each tab to hold a parent reference to the container so that it could get the container’s active tab, to see if ‘it’ was the active tab.

There is significant discussion about this online. The parent can be injected directly via its class name, but this introduces tight coupling which is undesirable.

Another option discussed was the use of @Host in conjunction with injection, as per the angular docs here. In this case, the traversal of the injector  tree stops at the parent otherwise another compatible component could conceivably be injected from elsewhere.

My solution initially was to define parent and child interfaces which defined the interaction between them, as one would in Java. This decoupled them from each other. However, in Angular you cannot inject interfaces directly as they are not available at runtime. As I was already iterating the content children (the tabs) in the parent container, in the ngAfterContentInit() lifecycle hook (as this is the earliest point at which the content children are available), it was straightforward to manually assign the parent reference to each child via a method in the child interface. In this way the parent and children were decoupled – any parent supporting the container interface (used by the child) could host any children which used the child interface (used by the parent).

In the end I dumped the idea as it ended up a tad unwieldy – I only needed the child to detect if it was the active one and it was having to call a parent method to compare itself with the currently active tab to see if it was the one. This child element property was then used to ensure that only the content of the active tab was actually rendered. I finally just added a boolean active property on the child interface, and in the parent, when switching tabs, I cleared the active flag on the old active tab (if there was one) and set the active flag on the new active tab, as well as assigning a parent property for the currently active tab. Whilst this meant I was having to track the active flags correctly, I no longer had to handle parent references and parent method calls. This seemed less messy but it was a close call and either pattern in reality would be ok.

One point of note is that in Typescript, an interface can contain properties (as in fields in Java) as well as methods, so for example my interface for the child could contain active and default properties directly rather than having to additionally define isActive() and isDefault() methods.

No Comments »

May 15th, 2017
1:46 pm
Angular–dynamic building of parent component markup based on content children

Posted under Angular
Tags ,

I had a use case where I was rolling my own simple tab container.

An interesting challenge of this use case was the fact that the tabs needed rendering in their own right, but also needed iterating separately in order to build the tab header bar.

This is an example use case where content markup might influence parent markup dynamically and in multiple areas, and that attributes of the content markup are used in parent markup.

To do this I used the @ContentChildren decorator to inject an array of the tabs into the parent tab container. I could then easily iterate the array in the parent markup to build the header bar with labels and icons declared in the content children. In addition, the content children were rendered in their own right with their own content in different ways using <ng-content select=”…”></ng-content>.

No Comments »

May 14th, 2017
10:57 am
List of Icons to use with PrimeNG

Posted under Angular & PrimeNG
Tags ,

Prime now use Font Awesome for icons. They do not appear to be listed in the PrimeNG documentation/showcase, but are listed in the PrimeFaces one and may therefore be found here.

No Comments »

May 14th, 2017
10:53 am
Web App container layout– how to fill space to right

Posted under Angular & CSS & PrimeNG
Tags , ,

I was trying to allow a left div for a menu to have a percentage width, possibly with a fixed min-width.

I then wanted to add a right div which filled all the remaining space to the right, to form a content pane.

My initial attempts which failed were:-

1/ Float both divs left – this partly works e.g. if I gave 25% width to the left and 75% width to the right, i.e. I had to assign width. If I then gave a min-width to the left, the right div drops underneath when the min-width kicks in.

2/ Per this post here, I took the float out of the right div. Whilst it extended to fill the right hand space, it also filled the left hand space, and placing e.g. a PrimeNG toolbar in the right hand pane resulted in a mess where the height of the toolbar filled the whole height of both divs. This was all due to the interaction of the floated and non floated div – the non floated one just flowed around the left hand floated div, and its content was in fact also hiding underneath the right one. In fact the comments mention that the proposed solution in the post does not work exactly as I found.

Finally an interesting solution which did work is this post here. The right float is not floated but is set to overflow:hidden. This triggers a Block Formatting Context, which interacts with the float to fill the remaining space. The right div becomes a BFC which prevents sibling floats from intruding on them, and also prevents descendant floats from escaping. The post explains the details on this well.

This worked correctly, even when the min-width was used in conjunction with a percentage width for the left div. A plunker showing a simple example of the BFC may be found here.

In the end I abandoned this approach of rolling my own layout. I was using PrimeNG components, and PrimeNG comes with a Grid CSS layout component which does full responsive 12 column based layout. It is nestable, and adaptable automatically for different screen widths via media queries. It is also used internally for the PrimeNG components, so will play nicely with them and will be less prone to side effects. I note from the comments that Bootstrap responsive column layout does not work well with PrimeNG, so I stuck with PrimeNG as it is flexible and easy to use.

Another alternative for grid layout which is big in this area is Foundation, which is also reviewed and compared with Bootstrap here. Bootstrap may be found here. Both Foundation and Bootstrap are frameworks offering components and css/theming as well as grid layout so would likely fight with Primefaces as this post indicates. It looks like you may be able to just get the grid with Foundation by now, not sure with Bootstrap.

No Comments »

May 11th, 2017
10:25 am
Angular-cli error on ng build: “The "@angular/compiler-cli" package was not properly installed.”

Posted under Angular & PrimeNG
Tags ,

I got this error when trying to build and run the primeng-quickstart-cli per the readme in the git project

E:\Dev\angular\primeng-quickstart-cli>ng build
You seem to not be depending on "@angular/core". This is an error.

E:\Dev\angular\primeng-quickstart-cli>ng serve
The "@angular/compiler-cli" package was not properly installed.
Error: The "@angular/compiler-cli" package was not properly installed.
    at Object.<anonymous> (E:\Dev\angular\primeng-quickstart-cli\node_modules\@ngtools\webpack\src\index.js:14:11)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)
    at Object.<anonymous> (E:\Dev\angular\primeng-quickstart-cli\node_modules\@angular\cli\tasks\eject.js:10:19)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)

E:\Dev\angular\primeng-quickstart-cli>

I tried upgrading angular-cli as per here, but this did not solve the problem.

Interestingly when I tried to start the alternative primeng-quickstart-webpack project using ng-serve, I got the same error as above.

However, when following the correct (and different) instructions for primeng-quickstart-webpack  as follows it worked:-

npm install

npm run start:webpack

I therefore tried to use these npm install/run commands on the primeng-quickstart-cli project but it was clearly not set up for this build/run mechanism:-

E:\Dev\angular\primeng-quickstart-cli>npm run start:webpack
npm ERR! Windows_NT 6.1.7601
npm ERR! argv "E:\\Program Files\\nodejs\\node.exe" "E:\\Program Files\\nodejs\\node_modules\\n
npm ERR! node v7.10.0
npm ERR! npm  v4.2.0

npm ERR! missing script: start:webpack
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>

npm ERR! Please include the following file with any support request:
npm ERR!     C:\Users\SteveW\AppData\Roaming\npm-cache\_logs\2017-05-11T10_08_50_957Z-debug.log

At present the issue with primeng-quickstart-cli is not a blocking one – the other starter  primeng-quickstart-webpack looks preferable as it is a simple full CRUD table app whereas the other starter it a trivial one whch just outputs a message in response to a button click.

These StackOverflow posts here and here discuss the error, but I did not appear to be missing the basic config. This post might be more relevant, and advises downgrading first then re-upgrading, but it refers to angular 2 rather than 4.

I hope to learn and resolve these build issues and errors at some point soon though and gain a better understanding of what is going on/ what are the alternatives.

No Comments »