Migrating ASP.Net MVC PartialViews to Angular2

April 24, 2016

An Angular2 @Component combines the equivalents of MVC Controller and View. This mostly also applies to MVC PartialViews.

In my application, TypeScript dynamically adds PartialViews to the page’s HTML.

Migrating the code to Angular2, the page’s component, let’s call it ParentComponent, contains an array of ChildComponents. If a new ChildComponent is added to the array, Angular2 will automatically render its template or templateURL, and add the resulting HTML inside the <childcomponent> tag

<childcomponent *ngFor="#c of childcomponents" [childdata]="c">
</childcomponent>

Your custom JavaScript code can then process the rendered component in one of the LifeCycle Hooks.

The story gets more complicated if your code needs to dynamically select which PartialView to render. Of course, there is the NgSwitch directive, which acts as the templating’s switch/case mechanism, but template code may easily get ugly and overly complex.

The alternative is to define the template or templateURL programmatically by calling loader.loadIntoLocation() of DynamicComponentLoader, but, as GitHub issues show (#7815, #6701, #7596, #2753), this is not as straight-forward as one might hope, especially if template data-binding is involved (#6223, #7453SO, SO).

The solution that I extracted from the referenced issues looks like this

constructor(private loader: DynamicComponentLoader, 
    private elementRef: ElementRef, 
    private ref: ChangeDetectorRef) {
  this.myData = ..some data..;
  this.myOtherData = ..some data..;
}

ngOnInit() {
  var templateURL = .... calculate template ...;

  this.loader.loadIntoLocation(
    this.toComponent(templateURL + '.html', null),
    this.elementRef, 'newItem'
  ).then(component => { 
    component.instance.myData = this.myData;
    component.instance.myOtherData = this.myOtherData;
    this.ref.markForCheck() 
  }); 
}

Based on SO and plnkr

toComponent(templateUrl, directives = []) {
  @Component({ selector: 'child-fake-component', 
  templateUrl: templateUrl,
  directives: [COMMON_DIRECTIVES])
  class ChildFakeComponent {}
 
  return ChildFakeComponent;
}

Note that I need ChangeDetectorRef to explicitly update the template because I deactivated change detection using ChangeDetectionStrategy.OnPush, so this need not apply to your case.

The essential part is that you need to copy all data referenced by the template to component.instance. #newItem is the anchor of the HTML element in the @Component’s template or template, and the loaded template will be attached after the original template, not replacing the original template.


Invoking Custom JavaScript Code from Angular2

April 22, 2016

I am trying to migrate an ASP.Net MVC application to Angular2. One thing I am still missing is how to invoke custom/legacy JavaScript code, as Angular2 does not render <script> tags contained in templates.

Actually we do not need <script> tags, as custom JavaScript/TypeScript can be called from the @Component!

Custom code can be invoked from various places of your component’s TypeScript code:

Logging to the console shows that code is executed in the following order

  • constructor
  • ngAfterContentInit
  • ngAfterViewInit
  • asynchronous code invoked in constructor (e.g. by http.get())

(for more details, see Angular’s documentation of Lifecycle Hooks)

Since executed code resides in the @Component, we do not need to pass JavaScript objects to the template.

Whereas in ASP.Net MVC we have a strict distinction between Controller and View, and process and data flow are from the controller to the view, and the view cannot (usually does not) reference the controller, this distinction does not apply in Angular2, where we end up in the component after the template has been rendered.


Angular2 “Does not support more than 9 expressions”

April 21, 2016

If you need to pass more than just a couple of values from your Angular2 component to the template, you’ll sooner or later run into the error message

EXCEPTION: Does not support more than 9 expressions

I needed to do just that to provide TypeScript/JavaScript objects with a huge set of values. The solution to work around this restriction is to create an object in the component which stores all these values, and then access its JSONified value

export class MyComponent {
  o: any;

  constructor() {
    var o = { .... complex JavaScript object ... };
    this.o = JSON.stringify(o);
  }
}

from the template

< script >
  var o = {{ o }};
  ....
</script >

…except that <script> tags are not rendered in Angular2 templates.

We can still store the JSONified value in an HTML attribute. But to call custom or legacy JavaScript code, we can extend the @Component.


The selector “my-app” did not match any elements

April 21, 2016

Developing my first Angular2 application (baby steps, baby steps), I edit code and, without any changes in the core files (index.html, app.ts, main.ts, etc), the application suddenly won’t start up, and the browser console displays the error message

The selector “my-app” did not match any elements

and an impressive stack dump

angular2.dev.js:23935 EXCEPTION: The selector "my-app" did not match any elements
angular2.dev.js:23925 EXCEPTION: The selector "my-app" did not match any elementsBrowserDomAdapter.logError @ angular2.dev.js:23925
angular2.dev.js:23935 EXCEPTION: Error: Uncaught (in promise): The selector "my-app" did not match any elements
angular2.dev.js:23925 EXCEPTION: Error: Uncaught (in promise): The selector "my-app" did not match any elementsBrowserDomAdapter.logError @ angular2.dev.js:23925
angular2.dev.js:23925 STACKTRACE:BrowserDomAdapter.logError @ angular2.dev.js:23925
angular2.dev.js:23925 Error: Uncaught (in promise): The selector "my-app" did not match any elements
 at resolvePromise (angular2-polyfills.js:602)
 at angular2-polyfills.js:638
 at ZoneDelegate.invokeTask (angular2-polyfills.js:423)
 at Object.NgZoneImpl.inner.inner.fork.onInvokeTask (angular2.dev.js:2118)
 at ZoneDelegate.invokeTask (angular2-polyfills.js:422)
 at Zone.runTask (angular2-polyfills.js:320)
 at drainMicroTaskQueue (angular2-polyfills.js:541)
 at XMLHttpRequest.ZoneTask.invoke (angular2-polyfills.js:493)BrowserDomAdapter.logError @ angular2.dev.js:23925
angular2-polyfills.js:528 Unhandled Promise rejection: The selector "my-app" did not match any elements ; Zone: angular ; Task: Promise.then ; Value: BaseExceptionmessage: "The selector "my-app" did not match any elements"stack: "Error: The selector "my-app" did not match any elements? at new BaseException (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:7587:21)? at DomRenderer.selectRootElement (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:13997:15)? at DebugDomRenderer.selectRootElement (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:7393:37)? at HostViewFactory.viewFactory_HostAppComponent0 [as viewFactory] (viewFactory_HostAppComponent:72:18)? at AppViewManager_.createRootHostView (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:6665:34)? at http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:12521:46? at ZoneDelegate.invoke (http://localhost:3000/node_modules/angular2/bundles/angular2-polyfills.js:390:29)? at Object.NgZoneImpl.inner.inner.fork.onInvoke (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:2126:31)? at ZoneDelegate.invoke (http://localhost:3000/node_modules/angular2/bundles/angular2-polyfills.js:389:35)? at Zone.run (http://localhost:3000/node_modules/angular2/bundles/angular2-polyfills.js:283:44)"__proto__: ErrorconsoleError @ angular2-polyfills.js:528
angular2-polyfills.js:530 Error: Uncaught (in promise): The selector "my-app" did not match any elements(…)consoleError @ angular2-polyfills.js:530
angular2-polyfills.js:528 Unhandled Promise rejection: The selector "my-app" did not match any elements ; Zone: <root> ; Task: Promise.then ; Value: BaseExceptionmessage: "The selector "my-app" did not match any elements"stack: "Error: The selector "my-app" did not match any elements? at new BaseException (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:7587:21)? at DomRenderer.selectRootElement (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:13997:15)? at DebugDomRenderer.selectRootElement (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:7393:37)? at HostViewFactory.viewFactory_HostAppComponent0 [as viewFactory] (viewFactory_HostAppComponent:72:18)? at AppViewManager_.createRootHostView (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:6665:34)? at http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:12521:46? at ZoneDelegate.invoke (http://localhost:3000/node_modules/angular2/bundles/angular2-polyfills.js:390:29)? at Object.NgZoneImpl.inner.inner.fork.onInvoke (http://localhost:3000/node_modules/angular2/bundles/angular2.dev.js:2126:31)? at ZoneDelegate.invoke (http://localhost:3000/node_modules/angular2/bundles/angular2-polyfills.js:389:35)? at Zone.run (http://localhost:3000/node_modules/angular2/bundles/angular2-polyfills.js:283:44)"__proto__: ErrorconsoleError @ angular2-polyfills.js:528
angular2-polyfills.js:530 Error: Uncaught (in promise): The selector "my-app" did not match any elements(…)consoleError @ angular2-polyfills.js:530

Opening another browser instance with the same URL does not raise any errors.

Strange.

Replacing the line

 System.import('app/main')

in index.html with

 System.import('./app/main')

seems to fix this behavior – for now, at least.

Update: Seems that joy was premature.

The only way to resolve this condition as of Angular 2.0.0-beta.15 seems to be

  • close the web browser tab
  • cancel npm lite-server
  • restart lite-server using npm start
  • completely reload page in browser developer mode

Mapping URL Querystring Parameters to Parameter Model Classes in Angular2

April 20, 2016

In ASP.Net MVC we can define a parameter model class, which is automatically filled by the framework before invocation of the controller’s method implementing the action. (More precisely, the Databinder sets the values of the public properties of the object)

public class QueryStringParameters 
{
  public int Id { get; set; }
  public string Foo  { get; set; }
  public string Bar  { get; set; }
}

Angular2 does not seem to provide such a mechanism out of the box. I found 3 classes handling URL parameters, and there are probably more

  • import { RouteParams } from 'angular2/router';
  • import { URLSearchParams } from 'angular2/http';
  • UrlParser in angular2/ts/src/router/url_parser

where UrlParser cannot be imported in TypeScript code.

So I tried to figure out how to use RouteParams and URLSearchParams and, using the URL http://localhost:3000/default?id=3&foo=8&bar=4711, found these differences:

routeParams.params

routeParams.params

URLSearchParams

URLSearchParams

Whereas routeParams.params is a simple Object with propery names derived from the query string, URLSearchParams contains a Map<string, string[]> (see url_search_params.d.ts in node_modules\angular2\src\http).

I chose routeParams to continue, because I do not use multiple occurrences of URL parameters.

URL parameters are case-sensitive in Angular2 / TypeScript / JavaScript, whereas they are case-insensitive in ASP.Net MVC. To copy the query string parameter values into a model class, a method to ignore case of both the URL parameters and the model class properties is therefore necessary.

To get the names of the parameters, we can use the function Object.keys() applied on routeParams.params, and we map the lower-case version of the name to the name.

Next, we iterate through the Object.keys of the parameter model class, and assign the model class property the value given by the query string parameter if one exists:

import {RouteParams} from 'angular2/router';

export function fromRouteParams<T>(model: T, routeParams: RouteParams): T {
  var rk = [];
  Object.keys(routeParams.params).forEach(k => { rk[k.toLowerCase()] = k; });

  var mk = Object.keys(model);
  mk.forEach(
    k => {
      if (rk.indexOf[k.toLowerCase()] != -1)
      model[k] = routeParams.get(rk[k.toLowerCase()]);
  });

  return model;
}

Finally, given the TypeScript parameter model class

export class QueryStringParameters {
  public Id: number = null;
  public Foo: number = null;
  public Bar: number = null;
}

the component defined as

import {RouteParams} from 'angular2/router';
import {QueryStringParameters} from './model/QueryStringParameters';
import {fromRouteParams} from './helpers/routeParamsHelpers';
export class DefaultComponent { 
  private q: QueryStringParameters; 
  constructor(routeParams: RouteParams) {
    this.q = fromRouteParams(new QueryStringParameters(), routeParams);
  }
}

containing a simple Angular2 template

template: `Id: {{ q.Id }}, Bar: {{ q.Bar }}, Foo: {{ q.Foo }}`

we can navigate to the URL http://localhost:3000/default?id=3&foo=8&bar=4711 and view the resulting HTML:

Id: 3, Bar: 4711, Foo: 8

Note that my function does not perform type checks on the model class properties, as it just copies the original parameter string values.


Getting Started with Visual Studio Code and Angular2

April 18, 2016

Version 1.0 of Visual Studio Code has been released. Time to give it a try along with TypeScript and Angular2.

  • Download and install Visual Studio Code
  • Run Visual Studio Code
  • Check your settings regarding Updates and Telemetry (i.e. “phoning home”), and everything else
  • VS Code will start with the OS’es locale it it is supported. To change to English, create the file locale.json in your user directory C:\Users\[UserName]\AppData\Roaming\Code\User containing the lines
{
"locale":"en"
}

nodejs firewall


Which Version of TypeScript does Visual Studio use?

April 14, 2016

I really love TypeScript.

I started out with version 0.8 in VS 2010 because of a (mostly) client-side web project. I always tried to avoid JavaScript because I prefer programming languages that compile, and I found that finally TypeScript was the way to go.

Projects live on, and VS 2013 got installed on the PC, along with (manually installed) TypeScript 1.4. Now colleagues are already on VS 2015, and we need to have the same TypeScript compiler. So which version of TypeScript does Visual Studio use?

ts2013

No indication that version 1.4 is installed

As far as I’m aware, VS 2013 does not provide the means to display the currently used TypeScript version. Answers to a related question on SO suggest to

  • open cmd and run tsc -v
  • use VS Command Prompt and run tsc -v
  • open the Package Manager Console and run tsc -v

but the always result in the message

Unknown option ‘v’

What’s going on here?

TypeScript is installed under C:\Program Files\Microsoft SDKs\TypeScript (or C:\Program Files (x86)\Microsoft SDKs\TypeScript on 64-bit Windows). To my surprise, I found 3 versions installed: 0.8.0.0, 1.0, 1.4, but the list of installed software in Programs and Features only listed 0.8.0.0 (“TypeScript for Microsoft VS 2012”) and 1.4.

Where did TypeScript version 1.0 come from? Apparently it got installed while applying VS2013 Update 5, judging from the directory timestamps. Oops: It might also have been installed with VS2013, and some timestamps updated during upgrade.

Different versions, different help message

This is the output if you run tsc from the directory 0.8.0.0:

Syntax:   tsc [options] [file ..]

Examples: tsc hello.ts
          tsc --out foo.js foo.ts
          tsc @args.txt

Options:
  -c, --comments  Emit comments to output
  --declarations  Generates corresponding .d.ts file
  -e, --exec      Execute the script after compilation
  -h, --help      Print this message
  --module KIND   Specify module code generation: "commonjs" (default) or "amd"
  --nolib         Do not include a default lib.d.ts with global declarations
  --out FILE      Concatenate and emit output to single file
  --target VER    Specify ECMAScript target version: "ES3" (default), or "ES5"
  @<file>         Insert command line options and files from a file.

Note that there is no '-v' option!

This is the output of tsc run from directory 1.0:

Version 1.0.3.0
Syntax:   tsc [options] [file ..]

Examples: tsc hello.ts
          tsc --out foo.js foo.ts
          tsc @args.txt

Options:
  --codepage NUMBER             Specify the codepage to use when opening source
files.
  -d, --declaration             Generates corresponding .d.ts file.
  -h, --help                    Print this message.
  --mapRoot LOCATION            Specifies the location where debugger should loc
ate map files instead of generated locations.
  -m KIND, --module KIND        Specify module code generation: 'commonjs' or 'a
md'
  --noImplicitAny               Warn on expressions and declarations with an imp
lied 'any' type.
  --out FILE                    Concatenate and emit output to single file.
  --outDir DIRECTORY            Redirect output structure to the directory.
  --removeComments              Do not emit comments to output.
  --sourcemap                   Generates corresponding .map file.
  --sourceRoot LOCATION         Specifies the location where debugger should loc
ate TypeScript files instead of source locations.
  -t VERSION, --target VERSION  Specify ECMAScript target version: 'ES3' (defaul
t), or 'ES5'
  -v, --version                 Print the compiler's version: 1.0.3.0
  @<file>                       Insert command line options and files from a fil
e.

tsc -v results in

Version 1.0.3.0

This is the output of tsc run from directory 1.4:

Version 1.4.0.0
Syntax:   tsc [options] [file ...]

Examples: tsc hello.ts
          tsc --out file.js file.ts
          tsc @args.txt

Options:
 -d, --declaration                 Generates corresponding '.d.ts' file.
 -h, --help                        Print this message.
 --mapRoot LOCATION                Specifies the location where debugger should
locate map files instead of generated locations.
 -m KIND, --module KIND            Specify module code generation: 'commonjs' or
 'amd'
 --noEmitOnError                   Do not emit outputs if any type checking erro
rs were reported.
 --noImplicitAny                   Warn on expressions and declarations with an
implied 'any' type.
 --out FILE                        Concatenate and emit output to single file.
 --outDir DIRECTORY                Redirect output structure to the directory.
 --preserveConstEnums              Do not erase const enum declarations in gener
ated code.
 --removeComments                  Do not emit comments to output.
 --sourceMap                       Generates corresponding '.map' file.
 --sourceRoot LOCATION             Specifies the location where debugger should
locate TypeScript files instead of source locations.
 --suppressImplicitAnyIndexErrors  Suppress noImplicitAny errors for indexing ob
jects lacking index signatures.
 -t VERSION, --target VERSION      Specify ECMAScript target version: 'ES3' (def
ault), 'ES5', or 'ES6' (experimental)
 -v, --version                     Print the compiler's version.
 -w, --watch                       Watch input files.
 @<file>                           Insert command line options and files from a
file.

tsc -v results in

message TS6029: Version 1.4.0.0

Due to whatever installation magic the installers perform, the PATH environment variable contains the directories related to TypeScript in this order:

C:\Program Files\Microsoft SDKs\TypeScript\0.8.0.0\;
C:\Program Files\Microsoft SDKs\TypeScript\1.0\;
C:\Program Files\Microsoft SDKs\TypeScript\1.4\;

which explains why the oldest version of TypeScript is called when invoked from command line.

This sequence is the same in Visual Studio Command Prompt (2010), which is OK due to compatibility. But the Developer Command prompt for VS2013 prepends version 1.0, resulting in

C:\Program Files\Microsoft SDKs\TypeScript\1.0\;
C:\Program Files\Microsoft SDKs\TypeScript\0.8.0.0\;
C:\Program Files\Microsoft SDKs\TypeScript\1.0\;
C:\Program Files\Microsoft SDKs\TypeScript\1.4\;

This is because the VsDevCmd.bat – which initializes all VS-related paths and environment variables – checks for version 1.0, but no higher version:

@rem Add path to TypeScript Compiler
@if exist "%ProgramFiles%\Microsoft SDKs\TypeScript\1.0" set PATH=%ProgramFiles%\Microsoft SDKs\TypeScript\1.0;%PATH%
@if exist "%ProgramFiles(x86)%\Microsoft SDKs\TypeScript\1.0" set PATH=%ProgramFiles(x86)%\Microsoft SDKs\TypeScript\1.0;%PATH%

And my project?

And just in case you’re wondering which version of TypeScript your project is using, open its .csproj file in a text editor and search for TypeScript:

    <TypeScriptToolsVersion>1.4</TypeScriptToolsVersion>

Blogger Allen Conway had similar experience regarding this question.