2017年2月13日 星期一

[Angular] Upgrade Angular CLI issues

 Angular2    Angular/CLI    Upgrade    issues  


Upgrade Angular/Cli


Notice that angular team move the npm package from angular-cli to @angular/cli.

You can use the following commands to upgrade it.

Uninstall

$> npm uninstall -g angular-cli
$> npm cache clean

Install

$> npm install -g @angular/cli


Solve the issues


Here are some issues with my existed project when upgrading Angular CLI to 1.0.0-beta.31.

1. ng serve not working
2. ng build not working





The reason why ng serve and ng build don’t work because the global Angular CLI is updated to the new version and the earlier angular modules/packages are not compatible with it.

So we have to use the local Angular CLI (the old one fit our project) to run the command.

Update package.json

Add the following script into the “scripts” section in package.json

"ng": "ng"


Just like this…

"scripts": {
    "start": "ng serve",
    "build": "ng build --prod",
    "ng": "ng",
    "lint": "tslint \"src/**/*.ts\"",
    "test": "ng test",
    "pree2e": "webdriver-manager update",
    "e2e": "protractor"
  }

Thus we could use the following command with the local Angular CLI.

$> npm run ng


Examples,

npm run ng serve
npm run ng build --prod


Furthermore, we could ease our command by adding something into package.json like this

"scripts": {
    "start": "ng serve",
    "build": "ng build --prod",
    "ng": "ng",
    "lint": "tslint \"src/**/*.ts\"",
    "test": "ng test",
    "pree2e": "webdriver-manager update",
    "e2e": "protractor"
  }

And just type the following command to build the angular app!

npm run build




Reference



2017年2月9日 星期四

[Angular] Use Sanitizer to ensure safe html string

 Angular    Sanitizer     Directive  


Introduction


In AngularJS, you may use $sanitize to ensure the safe html.
In Angular2, we will use Sanitizer class to do the same thing, the following is a simple sample and we will create a directive to enhance [innerHtml].


Environment
angular 2: 2.1.0


Implement


How to use Sanitizer

app.component.ts

import { Sanitizer, SecurityContext } from '@angular/core';

constructor(private sanitizer: Sanitizer) {
    let safeHtml = this.sanitizer.sanitize(SecurityContext.HTML, "<script>alert('I am bad!')</script>");
}


HTML

<input type="text" [(ngModel)]="safeHtml" />


Result:







Directive


import { Directive, ElementRef, Input, ViewContainerRef, Compiler, OnChanges, Sanitizer, SecurityContext } from '@angular/core';

@Directive({
    selector: '[safe-html]'
})
export class SafeHtml implements OnChanges {
    @Input() html: string;

    constructor(private elementRef: ElementRef, private sanitizer: Sanitizer) {


    }

    ngOnChanges() {

        if (this.html) {
            this.elementRef.nativeElement.innerHTML =
                this.sanitizer.sanitize(SecurityContext.HTML, this.html);
        }
    }
}


Usage

<div safe-html [html]="htmlStr"></div>



Reference