Angular

Paquests a instal·lar:

    npm install -g typescript
    npm install -g @angular/cli
    (si volem indicar la versió concreta: "@angular/cli@1.0.0")

Angular CLI

Les opcions de Angular CLI son:

Les opcions de "genereate" son:

Inicialitzar un projecte:

Testejar un projecte:

Publicar un projecte:

El codi font el trobarem al directori "dist" (Atenció! el index.html té l'atribut base href="/" i els fitxers aniran a cercar-se a la base del servidor web)

Crear un component:

Ens el publicarà a "src/app/" i ens actualitzarà "src/app/app.module.ts"

Crear un model in un component:

    ng generate module party
    ng generate component party-detail --module party

Estructura d'una app angular

Estructura base app

Al crear un projecte amb "ng new -ng4" ens crearà els fitxers, on el directori "src" conté el codi font:

    src/app/app.module.ts
    src/app/app.component.css
    src/app/app.component.html
    src/app/app.component.spec.ts
    src/app/app.component.ts
    src/assets
    src/environments
    src/favicon.ico
    src/index.html
    src/main.ts
    src/polyfills.ts
    src/styles.css
    src/test.ts
    src/tsconfig.app.json
    src/tsconfig.spec.json
    src/typings.d.ts

index.html

<base href="/"> // <- base uri de la nostra aplicació
<app-root></app-root> // <- base de la nostre app

Estructura d'un component

Al crear un component amb "ng g component my-component", ens crearà l'estructura:

    src/app/my-component/my-component.component.css
    src/app/my-component/my-component.component.html
    src/app/my-component/my-component.component.spec.ts
    src/app/my-component/my-component.component.ts
    src/app/app.module.ts

Per incloure el nostres components a l'aplicació ho afegirem a:

<app-my-component></app-my-component>
<app-my-component2></app-my-component2>
...

Per cada component que es crea es carrega a:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { HelloWorldComponent } from './hello-world/hello-world.component';
import { UserItemComponent } from './user-item/user-item.component';
import { UserListComponent } from './user-list/user-list.component';

@NgModule({
  declarations: [
    AppComponent,
    HelloWorldComponent,
    UserItemComponent,
    UserListComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Definir el nostre component

La definició del component ho definirem a:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css']
})
export class UserItemComponent implements OnInit {
  name: string;

  constructor() {
    this.name = 'Raimon';
  }

  ngOnInit() {
  }
}

I la plantilla del nostre componet la trobarem a:

<p>
  my-component works!
  Hello {{ name }}
</p>

Incloure un component dins d'un altre component

Per exemple el component "user-list":

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css']
})
export class UserItemComponent implements OnInit {
  names: string[];

  constructor() {
    this.names = ['Iona', 'Viqui', 'Raimon'];
  }

  ngOnInit() {
  }
}

I a la plantilla podem incloure que renderitzi el component user-item:

<ul>

</ul>

Ara bé, al component "user-item" haurem de passar-li les dades. Per tant, eliminarem "this.name" i ha de ser un "Input()"

import {
  Component,
  OnInit,
  Input
} from '@angular/core';

@Component({
  selector: 'app-my-component',
  templateUrl: './user-item-component.component.html',
  styleUrls: ['./user-item.component.css']
})
export class UserItemComponent implements OnInit {
  @Input() name: string;

  constructor() {

  }

  ngOnInit() {
  }
}

I a la plantilla li passarem les variables/valors:

<ul>
  <li *ngFor="let userName of names">
    <app-user-item [name]="userName"></app-user-item>
  </li>
</ul>

Model

Part del model que podriem definir a "src/app/article/article.component.ts" el passariem al model.

alert: si afegim model, millor reiniciar el "ng serve" si el tenim en dansa.

En el article.component.ts l'importariem:

import { Article } from './article.model'; // <-- added

I el model "src/app/article/article.model.ts" ens quedaria:

export class Article {
  title: string;
  link: string;
  votes: number;

  constructor(title: string, link: string, votes?: number) {
    this.title = title;
    this.link = link;
    this.votes = votes || 0;
  }

  voteUp(): void {
    this.votes += 1;
  }

  voteDown(): void {
    this.votes -= 1;
  }

  // domain() is a utility function that extracts
  // the domain from a URL, which we'll explain shortly
  domain(): string {
    try {
      // e.g. http://foo.com/path/to/bar
      const domainAndPath: string = this.link.split('//')[1];
      // e.g. foo.com/path/to/bar
      return domainAndPath.split('/')[0];
    } catch (err) {
      return null;
    }
  }
}

Directives

NgFor

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-my-component',
  templateUrl: './my-component.component.html',
  styleUrls: ['./my-component.component.css']
})
export class UserItemComponent implements OnInit {
  names: string[];

  constructor() {
    this.names = ['Iona', 'Viqui', 'Raimon'];
  }

  ngOnInit() {
  }
}

<ul>
  <li *ngFor="let name of names">Hello {{name}}</li>
</ul>

Router

Passar paràmetres a la uri

  { path: 'product/:id', component: ProductDetailComponent, data: {prova: true}},

I per obetenir:

constructor(private activatedRoute: ActivatedRoute)

this.activatedRoute.params.subscribe(params => { console.log(params);});
this.activatedRoute.data.subscribe(v => console.log(v));

File-Saver

https://www.npmjs.com/package/file-saver

package.json

  "dependencies": {
    "file-saver": "^1.3.8"
   }

.ts

import { saveAs } from 'file-saver';

var file = new File(["Hello, world111!"], "hello world.txt", {type: "text/plain;charset=utf-8"});
saveAs(file);

IndexedDB

Material

Material Examples

Material Menu

<button mat-button [matMenuTriggerFor]="menu">Menu</button>
<mat-menu #menu="matMenu">
  <button mat-menu-item [matMenuTriggerFor]="prova" *ngFor="let category of categories"> {{ category.name }}
    <mat-menu #prova="matMenu">
      <button mat-menu-item [matMenuTriggerFor]="prova3" *ngFor="let category2 of category.childs" (click)="filterProductList(category2.id)">{{ category2.name }}
        <mat-menu #prova3="matMenu">
          <button mat-menu-item  *ngFor="let category3 of category2.childs" (click)="filterProductList(category3.id)">{{ category3.name }}</button>
        </mat-menu>
      </button>
    </mat-menu>
  </button>
</mat-menu>

<mat-list>
  <a mat-list-item (click)="showProductList()">
    <h4 mat-line>{{'All' | translate:lang }}</h4>
    <button mat-icon-button><mat-icon>more_vert</mat-icon></button>
    <mat-divider></mat-divider>
  </a>
  <a mat-list-item *ngFor="let category of categories">
    <h4 mat-line>{{ category.name }}</h4>
    <mat-menu #second="matMenu">
      <button mat-menu-item [matMenuTriggerFor]="third" *ngFor="let category2 of category.childs" (click)="filterProductList(category2.id)">{{ category2.name }}
        <mat-menu #third="matMenu">
          <button mat-menu-item  *ngFor="let category3 of category2.childs" (click)="filterProductList(category3.id)">{{ category3.name }}</button>
        </mat-menu>
      </button>
    </mat-menu>
    <button mat-icon-button [matMenuTriggerFor]="second"><mat-icon>more_vert</mat-icon></button>
    <mat-divider></mat-divider>
  </a>
</mat-list>

Flex-Layout

<div fxLayout="row" fxLayout.lt-md="column"  fxLayoutGap="10px">
  <div fxLayout.gt-md="row" fxLayout.lt-sm="column"  fxLayoutGap="10px" fxFlex="100"  fxFlex.gt-md="50">
    <div fxFlex.lt-md="50" fxFlex.lt-sm="100" >1</div>
    <div fxFlex.lt-md="50" fxFlex.lt-sm="100" >2</div>
  </div>
  <div fxLayout.gt-md="row" fxLayout.lt-sm="column" fxLayoutGap="10px" fxFlex="100"   fxFlex.gt-md="50">
    <div fxFlex.lt-md="50" fxFlex.lt-sm="100" >3</div>
    <div fxFlex.lt-md="50" fxFlex.lt-sm="100" >4</div>
  </div>
</div>

Images from IndexedDB

Ionic 2: Base64 encoded images rendering with unsafe: prefix

import {DomSanitizer} from '@angular/platform-browser';
 
@Component({
  templateUrl: 'somePage.html'
})
export class SomePage {
 
  constructor(
    public _DomSanitizer: DomSanitizer,
    ...
  ) {
  }

<img mat-card-lg-image [src]="_DomSanitizer.bypassSecurityTrustUrl('data:image/jpeg;base64,'+template.image)" alt="{{ template.name }}">

Load documents static

import { Observable } from 'rxjs/Observable';
import { Http, Response, RequestOptions, Headers } from '@angular/http';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

export class ProductDetailComponent implements OnInit {
  myTemplate: SafeHtml;
  }

  constructor(private http: Http, public _DomSanitizer: DomSanitizer)

  loadTemplate(): Observable<Response> {
    return this.http.get('/assets/prova.html');
  }

  ngOnInit() {
    this.loadTemplate().subscribe(res => {
      // this.myTemplate = res.json();
      this.myTemplate = this._DomSanitizer.bypassSecurityTrustHtml(res.text());
      // console.log(this.myTemplate);
    });
}

<div class="product-detail-cell scroll-container" [innerHTML]="myTemplate" *ngIf="myTemplate"></div>

.scroll-container {
  overflow-x: scroll;
}

Wake Lock

JS:

function printStatus() {
  document.getElementById("status").innerHTML = screen.keepAwake
    ? "enabled"
    : "disabled";
}

function toggle() {
  if ("keepAwake" in screen) {
    screen.keepAwake = !screen.keepAwake;
    printStatus();
  }
}

if ("keepAwake" in screen) {
  printStatus();
}

HTML:

<p>Wake Lock status is <b id="status">unknown (not supported)</b>.</p>
<p><button class="btn btn-default" onclick="toggle()">Toggle</button></p>

Referencies

Angular (last edited 2018-08-16 09:53:37 by resteve)

Contenidos creados por el equipo de Zikzakmedia. Creative Commons By-NC-SA

PythonZikzakmedia