Tuesday, November 21, 2017

start a new empty angular project


https://github.com/angular/flex-layout

in the end demo section, last one is good example


create a material.module.ts as below, than in app.module import it.
import { NgModule } from '@angular/core';
import {PlatformModule} from '@angular/cdk/platform';
import {ObserversModule} from '@angular/cdk/observers';

import {CdkTableModule} from '@angular/cdk/table';
import 'hammerjs';

import {
MatAutocompleteModule,


MatButtonModule,


MatButtonToggleModule,


MatCardModule,


MatCheckboxModule,


MatChipsModule,


MatDatepickerModule,


MatDialogModule,


MatExpansionModule,


MatGridListModule,


MatIconModule,


MatInputModule,


MatListModule,


MatMenuModule,


MatNativeDateModule,


MatPaginatorModule,


MatProgressBarModule,


MatProgressSpinnerModule,


MatRadioModule,


MatRippleModule,


MatSelectModule,


MatSidenavModule,


MatSliderModule,


MatSlideToggleModule,


MatSnackBarModule,


MatSortModule,


MatTableModule,


MatTabsModule,


MatToolbarModule,


MatTooltipModule,


MatStepperModule
} from '@angular/material';



const materialModule = [


CdkTableModule,


MatAutocompleteModule,


MatButtonModule,


MatButtonToggleModule,


MatCardModule,


MatCheckboxModule,


MatChipsModule,


MatStepperModule,


MatDatepickerModule,


MatDialogModule,


MatExpansionModule,


MatGridListModule,


MatIconModule,


MatInputModule,


MatListModule,


MatMenuModule,


MatNativeDateModule,


MatPaginatorModule,


MatProgressBarModule,


MatProgressSpinnerModule,


MatRadioModule,


MatRippleModule,


MatSelectModule,


MatSidenavModule,


MatSliderModule,


MatSlideToggleModule,


MatSnackBarModule,


MatSortModule,


MatTableModule,


MatTabsModule,


MatToolbarModule,


MatTooltipModule,


];



@NgModule({
exports: [
// export material modul


materialModule,

ObserversModule,
PlatformModule
]
})
export class CustomMaterialModule {}

in app.module.ts, just import above module
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { FlexLayoutModule } from '@angular/flex-layout';


import { AppComponent } from './app.component';
import { CustomMaterialModule } from './material.module';

@NgModule({
imports: [ BrowserModule, FormsModule, FlexLayoutModule, CustomMaterialModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }



========================================================================

create a new project (https://material.angular.io/guide/getting-started)

1) create a new empty angular project
ng new project-name

2) copy src/app folder from other project to our new project.
     It is app folder, not src

3) install material
    npm install --save @angular/material @angular/cdk
  npm install --save @angular/animations
    npm install --save hammerjs

4) style.css add
     @import "../node_modules/@angular/material/prebuilt-themes/indigo-pink.css";

     index.html add icon
      <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
     

5) import material to app module
     by add section below
       

const materialModules = [
    MatButtonModule,
    MatMenuModule,
    MatToolbarModule,
    MatIconModule,
    MatCardModule,
    MatSidenavModule,
    MatFormFieldModule,
    MatInputModule,
    MatTooltipModule
];
@NgModule({
  imports: [...materialModules],
  exports: [...materialModules],
  declarations: []
})
export class xxxxxxxxModule {
}

import { BrowserModule } from "@angular/platform-browser";

import { NgModule } from "@angular/core";
import { FormsModule } from "@angular/forms";
import { HttpModule } from "@angular/http";

import { AppComponent } from "./app.component";
import { AppRoutingModule } from "./app-routing.module";

import { PokemonListComponent } from "./pokemon/pokemon-list.component";
import { PokemonDetailComponent } from "./pokemon/pokemon-detail.component";
import { PokemonService } from "./pokemon/pokemon-service";



// ----------------- import ------ material angular ---------------

import {BrowserAnimationsModule} from '@angular/platform-browser/animations';

import {
MatAutocompleteModule,
MatButtonModule,
MatButtonToggleModule,
MatCardModule,
MatCheckboxModule,
MatChipsModule,
MatDatepickerModule,
MatDialogModule,
MatExpansionModule,
MatGridListModule,
MatIconModule,
MatInputModule,
MatListModule,
MatMenuModule,
MatNativeDateModule,
MatPaginatorModule,
MatProgressBarModule,
MatProgressSpinnerModule,
MatRadioModule,
MatRippleModule,
MatSelectModule,
MatSidenavModule,
MatSliderModule,
MatSlideToggleModule,
MatSnackBarModule,
MatSortModule,
MatTableModule,
MatTabsModule,
MatToolbarModule,
MatTooltipModule,
MatStepperModule,
} from '@angular/material';

import {CdkTableModule} from '@angular/cdk/table';
import 'hammerjs';

const materialModule = [
CdkTableModule,
MatAutocompleteModule,
MatButtonModule,
MatButtonToggleModule,
MatCardModule,
MatCheckboxModule,
MatChipsModule,
MatStepperModule,
MatDatepickerModule,
MatDialogModule,
MatExpansionModule,
MatGridListModule,
MatIconModule,
MatInputModule,
MatListModule,
MatMenuModule,
MatNativeDateModule,
MatPaginatorModule,
MatProgressBarModule,
MatProgressSpinnerModule,
MatRadioModule,
MatRippleModule,
MatSelectModule,
MatSidenavModule,
MatSliderModule,
MatSlideToggleModule,
MatSnackBarModule,
MatSortModule,
MatTableModule,
MatTabsModule,
MatToolbarModule,
MatTooltipModule,
];

// ------------ End ----- material angular ---------------


@NgModule({
imports: [
AppRoutingModule,
BrowserModule,
FormsModule,
HttpModule,
// import material modul
materialModule,
],


//exports:[materialModule],

declarations: [
AppComponent,
PokemonListComponent,
PokemonDetailComponent
],
providers: [
PokemonService
],
bootstrap: [AppComponent]
})
export class AppModule { }


6) vscode, ctrl+` will open internal cmd
    ng serve --port 4205


7) if compiled failed, from error message said missing some package.
     Do not go to source package.json, you should not edit copy and past missing package to new project package.json.
 
     instead you should run

         npm install xxxxx --save

      this will automatically update package.json for you.


   for hero project, you must run , because angular cli will not add it by default.
 npm install angular-in-memory-web-api --save
 
Angular CLI no longer uses SystemJS (replaced by Webpack), so systemjs.config.js no longer exists.



===========================================
ng new project-name

cd project-name

ng serve --host 0.0.0.0 --port 4201




========================
first check angular /cli version by


ng --verison


if you see error:

Your global Angular CLI version (1.6.5) is greater than your local
version (1.5.2). The local Angular CLI version is used.

run this, to update local cli

npm install --save-dev @angular/cli@latest

You must have angular/cli the latest version install both global and locally



-g means install globle
npm install -g @angular/cli

ng new my-app



cd my-app
ng serve --open




npm install

=====================================


run angular app on PHP


open cmd
1) cd your-project folder
2) ng build
3) copy dist folder to apache/htdocs/[dist/or your-project-name]
4) Important:  open the index.html file, find <base href="/">
change it to <base href="/your-project-name/">
Without doing this, js file will not be load correctly.

Wednesday, November 15, 2017

ngmodule, javascript module, method chain

how to use other module's component?



For example, I have M2 module, M2 module have comp23 component and comp2 component, Now I want to use comp23 and comp2 in app.module





// import this module's ALL component, but not other module's component, only this module
import { AppComponent } from './app.component';
import { Comp1Component } from './comp1/comp1.component';

// import all other module,
import { SwModule } from './sw/sw.module';
import { Sw1Module } from './sw1/sw1.module';
import { M2Module } from './m2/m2.module';

import { CustomerDashboardModule } from './customer-dashboard/customer-dashboard.module';


@NgModule({

// declare only this module's all component, not other module component.
declarations: [
AppComponent,
Comp1Component,

],

// imports all other module only.
imports: [
BrowserModule,
SwModule,
Sw1Module,
M2Module,
CustomerDashboardModule // add the feature module here
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }



import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

// must import this module's all component file
import { Comp2Component } from './comp2/comp2.component';
import { Comp23Component } from './comp23/comp23.component';

@NgModule({

// import all other module here.
imports: [
CommonModule
],

// declare only this module's child component.
declarations: [Comp2Component, Comp23Component],

// for other module to use these component, must exports
exports: [Comp2Component, Comp23Component]
})
export class M2Module { }

now in app.component.html, you can use
  

<app-tr111></app-tr111>

<app-wt></app-wt>

++++++++++++++++++++++++++++

<app-tr111></app-tr111>

<app-wt1></app-wt1>


=============================
<app-comp2></app-comp2>

<app-comp23></app-comp23>


======================================================================


// import {xx} from "./XXX" is ES6 module API,
 ./ is current folder, ../ is parent folder
 import some module and some component(only this module's child component),
not other module's component. If you want to use other module's component,
you only import other module here, it will automatically bring all child component
available here. of course, in other module, you need to exports:[child component]

import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { FormsModule } from "@angular/forms";
import { HttpModule } from "@angular/http";

import { AppComponent } from "./app.component";
import { AppRoutingModule } from "./app-routing.module";

import { PokemonListComponent } from "./pokemon/pokemon-list.component";

@NgModule({
  imports: [
 // all above ES6 imported module, need to be list here for NgModule
    AppRoutingModule,
    BrowserModule,
    FormsModule,
    HttpModule,
  ],
  declarations: [
// all above ES6 imported component, need to be list here for NgModule
    AppComponent,
    PokemonListComponent
  ],
  bootstrap: [AppComponent]
exports:[comp1, comp2] // if you want to use comp1, comp2 in other module, you
need to exports it. But for AppModule, it is root module, you do not need so

})
export class AppModule { }




=======================================================================

Method chain:
"return this" in each function.


JavaScript Module Pattern: In-Depth

Monday, November 13, 2017

javascript Anonymous functions, closures

Mastering the Module Pattern
Jan 29, 2014
9 mins read
Edit post






I’m a massive fan of JavaScript’s Module Pattern and I’d like to share some use cases and differences in the pattern, and why they’re important. The Module Pattern is what we’d call a “design pattern,”and it’s extremely useful for a vast amount of reasons. My main attraction to the Module Pattern (and its variant, the Revealing Module Pattern) is it makes scoping a breeze and doesn’t overcomplicate program design.
It also keeps things very simple and easy to read and use, uses Objects in a very nice way, and doesn’t bloat your code with repetitive this and prototype declarations. I thought I’d share some insight as to the awesome parts of the Module, and how you can master it, its variants and features.

Creating a Module



To understand what a Module can give you, you’ll need to understand what the following functionconcept does:


(function () {
  // code
})();

It declares a function, which then calls itself immediately. These are also known as Immediately-Invoked-Function-Expressions, in which the function creates new scope and creates “privacy”. JavaScript doesn’t have privacy, but creating new scope emulates this when we wrap all our function logic inside them. The idea then is to return only the parts we need, leaving the other code out of the global scope.
After creating new scope, we need to namespace our code so that we can access any methods we return. Let’s create a namespace for our anonymous Module.


var Module = (function () {
  // code
})();

We then have Module declared in the global scope, which means we can call it wherever we like, and even pass it into another Module.

Private methods



You’ll see and hear a lot about private methods in JavaScript. But Javascript doesn’t strictly have private methods, but we can create a working equivalent.
What are private methods you might be asking? Private methods are anything you don’t want users/devs/hackers to be able to see/call outside the scope they’re in. We might be making server calls and posting sensitive data, we don’t want to expose those functions publicly, they could post anything back then and take advantage of our code. So we can create closure and be more sensible (as best as we can with JavaScript) at protecting our code. It’s not all about protection however, there are also naming conflicts. I bet when you first started out writing jQuery/JavaScript, that you dumped all your code in one file and it was just function, function, function. Little did you know these were all global, and you probably suffered the consequence at some point. If so, you’ll learn why, and what to do to change it.
So let’s use our newly created Module scope to make our methods inaccessible outside of that scope. For beginners to the Module Pattern, this example will help understand how a private method would be defined:


var Module = (function () {
  
  var privateMethod = function () {
    // do something
  };

})();

The above example declares our function privateMethod, which is locally declared inside the new scope. If we were to attempt calling it anywhere outside of our module, we’ll get an error thrown and our JavaScript program will break! We don’t want anyone to be able to call our methods, especially ones that might manipulate data and go back and forth to a server.

Understanding “return”



Typical Modules will use return and return an Object to the Module, to which the methods bound to the Object will be accessible from the Module’s namespace.
A real light example of returning an Object with a function as a property:


var Module = (function () {
  
  return {
    publicMethod: function () {
      // code
    }
  };

})();

As we’re returning an Object Literal, we can call them exactly like Object Literals:


Module.publicMethod();

For those who haven’t used the Object Literal syntax before, a standard Object Literal could look something like this:


var myObjLiteral = {
  defaults: { name: 'Todd' },
  someMethod: function () {
    console.log(this.defaults);
  }
};

// console.log: Object { name: 'Todd' }
myObjLiteral.someMethod();

But the issue with Object Literals is the pattern can be abused. Methods intended to be “private” will be accessible by users because they are part of the Object. This is where the Module comes in to save us, by allowing us to define all our “private” stuff locally and only return “the good parts”.
Let’s look at a more Object Literal syntax, and a perfectly good Module Pattern and the return keyword’s role. Usually a Module will return an Object, but how that Object is defined and constructed is totally up to you. Depending on the project and the role/setup of the code, I may use one of a few syntaxes.

Anonymous Object Literal return



One of the easiest patterns is the same as we’ve declared above, the Object has no name declared locally, we just return an Object and that’s it:


var Module = (function () {

  var privateMethod = function () {};
  
  return {
    publicMethodOne: function () {
      // I can call `privateMethod()` you know...
    },
    publicMethodTwo: function () {

    },
    publicMethodThree: function () {

    }
  };

})();

Locally scoped Object Literal



Local scope means a variable/function declared inside a scope. On the Conditionizr project, we use a locally scoped namespace as the file is over 100 lines, so it’s good to be able to see what are the public and private methods without checking the return statement. In this sense, it’s much easier to see what ispublic, because they’ll have a locally scoped namespace attached:


var Module = (function () {

  // locally scoped Object
  var myObject = {};

  // declared with `var`, must be "private"
  var privateMethod = function () {};

  myObject.someMethod = function () {
    // take it away Mr. Public Method
  };
  
  return myObject;

})();

You’ll then see on the last line inside the Module that myObject is returned. Our global Module doesn’t care that the locally scoped Object has a name, we’ll only get the actual Object sent back, not the name. It offers for better code management.

Stacked locally scoped Object Literal



This is pretty much identical as the previous example, but uses the “traditional” single Object Literal notation:


var Module = (function () {

  var privateMethod = function () {};

  var myObject = {
    someMethod:  function () {

    },
    anotherMethod:  function () {
      
    }
  };
  
  return myObject;

})();

I prefer the second approach we looked at, the Locally scoped Object Literal. Because here, we have to declare other functions before we use them (you should do this, using function myFunction () {} hoists your functions and can cause issues when used incorrectly). Using var myFunction = function () {}; syntax lets us not worry about this, as we’ll declare them all before we use them, this also makes debugging easier as the JavaScript interpreter will render our code in the order we declare, rather than hoisting functiondeclarations. I also don’t like this approach so much, because the “stacking” method can often get verbose looking, and there is no obvious locally scoped Object namespace for me to bolt public methods onto.

Revealing Module Pattern



We’ve looked at the Module, and there’s a really neat variant which is deemed the “revealing” pattern, in which we reveal public pointers to methods inside the Module’s scope. This again, can create a really nice code management system in which you can clearly see and define which methods are shipped back to the Module:


var Module = (function () {

  var privateMethod = function () {
    // private
  };

  var someMethod = function () {
    // public
  };

  var anotherMethod = function () {
    // public
  };
  
  return {
    someMethod: someMethod,
    anotherMethod: anotherMethod
  };

})();

I really like the above syntax, as it’s very declarative. For bigger JavaScript Modules this pattern helps out a lot more, using a standard “Module Pattern” can get out of control depending on the syntax you go for and how you structure your code.

Accessing “Private” Methods



You might be thinking at some stage during this article, “So if I make some methods private, how can I call them?”. This is where JavaScript becomes even more awesome, and allows us to actually invoke private functions via our public methods. Observe:


var Module = (function () {

  var privateMethod = function (message) {
    console.log(message);
  };

  var publicMethod = function (text) {
    privateMethod(text);
  };
  
  return {
    publicMethod: publicMethod
  };

})();

// Example of passing data into a private method
// the private method will then `console.log()` 'Hello!'
Module.publicMethod('Hello!');

You’re not just limited to methods, though. You’ve access to Objects, Arrays, anything:


var Module = (function () {

  var privateArray = [];

  var publicMethod = function (somethingOfInterest) {
    privateArray.push(somethingOfInterest);
  };
  
  return {
    publicMethod: publicMethod
  };

})();

Augmenting Modules



So far we’ve created a nice Module, and returned an Object. But what if we wanted to extend our Module, and include another smaller Module, which extends our original Module?
Let’s assume the following code:


var Module = (function () {

  var privateMethod = function () {
    // private
  };

  var someMethod = function () {
    // public
  };

  var anotherMethod = function () {
    // public
  };
  
  return {
    someMethod: someMethod,
    anotherMethod: anotherMethod
  };

})();

Let’s imagine it’s part of our application, but by design we’ve decided to not include something into the core of our application, so we could include it as a standalone Module, creating an extension.
So far our Object for Module would look like:


Object {someMethod: function, anotherMethod: function}

But what if I want to add our Module extension, so it ends up with another public method, maybe like this:


Object {someMethod: function, anotherMethod: function, extension: function}

A third method is now available, but how do we manage it? Let’s create an aptly named ModuleTwo, and pass in our Module namespace, which gives us access to our Object to extend:


var ModuleTwo = (function (Module) {
    
    // access to `Module`
    
})(Module);

We could then create another method inside this module, have all the benefits of private scoping/functionality and then return our extension method. My pseudo code could look like this:


var ModuleTwo = (function (Module) {
    
    Module.extension = function () {
        // another method!
    };
    
    return Module;
    
})(Module || {});

Module gets passed into ModuleTwo, an extension method is added and then returned again. Our Object is getting thrown about, but that’s the flexibility of JavaScript :D
I can then see (through something like Chrome’s Dev Tools) that my initial Module now has a third property:


// Object {someMethod: function, anotherMethod: function, extension: function}
console.log(Module);

Another hint here, you’ll notice I’ve passed in Module || {} into my second ModuleTwo, this is incase Module is undefined - we don’t want to cause errors now do we ;). What this does is instantiate a newObject, and bind our extension method to it, and return it.

Private Naming Conventions



I personally love the Revealing Module Pattern, and as such, I have many functions dotting around my code that visually are all declared the same, and look the same when I’m scanning around. I sometimes create a locally scoped Object, but sometimes don’t. When I don’t, how can I distinguish between private variables/methods? The _ character! You’ve probably seen this dotted around the web, and now you know why we do it:


var Module = (function () {

  var _privateMethod = function () {
    // private stuff
  };

  var publicMethod = function () {
    _privateMethod();
  };
  
  return {
    publicMethod: publicMethod
  };

})();



ECMAScript



ECMA-262-3 in detail. Chapter 5. Functions


===========================================================
 whether you define a function like function foo(){} or var foo = function(){}, what you end up with is an identifier for a function, that you can invoke by putting parens (parentheses, ()) after it, like foo().
01.// Because a function defined like so can be invoked by putting () after
02.// the function name, like foo(), and because foo is just a reference to
03.// the function expression `function() { /* code */ }`...
04. 
05.var foo = function(){ /* code */ }
06. 
07.// ...doesn't it stand to reason that the function expression itself can
08.// be invoked, just by putting () after it?
09. 
10.function(){ /* code */ }(); // SyntaxError: Unexpected token (
As you can see, there’s a catch. When the parser encounters the function keyword in the global scope or inside a function, it treats it as a function declaration (statement), and not as a function expression, by default. If you don’t explicitly tell the parser to expect an expression, it sees what it thinks to be a function declaration without a name and throws a SyntaxError exception because function declarations require a name.
====================================================================
An anonymous function is just a function that has no name; nothing more. A closure is a function that captures the state of the surrounding environment.
An anonymous function does not necessarily need to create a closure, and a closure is not created only for anonymous functions.

Immediately-Invoked Function Expression (IIFE)

Fortunately, the SyntaxError “fix” is simple. The most widely accepted way to tell the parser to expect a function expression is just to wrap it in parens, because in JavaScript, parens can’t contain statements. At this point, when the parser encounters the function keyword, it knows to parse it as a function expression and not a function declaration.
01.// Either of the following two patterns can be used to immediately invoke
02.// a function expression, utilizing the function's execution context to
03.// create "privacy."
04. 
05.(function(){ /* code */ }()); // Crockford recommends this one
06.(function(){ /* code */ })(); // But this one works just as well
-------------------------------------------------------------------------------------
I have read a lot about closures in Javascript What are those braces for?? I read on mozilla.orgwhich says closure should be defined as
(function(){...})();
(function(){...}());
 what's the purpose of the last ()?
The syntax
(function(){...})()
is simply an immediately invoked anonymous function. It does not matter how you use your brackets, as the underlying code is a function being declared, and invoked.
The syntax
(function(){...})()
is simply an immediately invoked anonymous function. It does not matter how you use your brackets, as the underlying code is a function being declared, and invoked.
Closures are instead used to describe a situation where a function has access to variables declared outside of its scope, accessible via closures
For clarity :
If we have the following function
   function hello() {
      alert("Hello");
   }
We can call the function with the following
hello()
Which invokes the function 'hello'. But if we do not wish to give it a name, but still invoke it, then we can do
(function hello() {
   alert("Hello");
})()
Which will do the exact same as the previous example of calling hello
However, in this scenario there is no point in giving the function the name 'hello', so we can simply remove it:
(function() {
    alert("Hello");
})()

------------------------------------------

Closures define:

JavaScript, Anonymous Function, Closure


https://jaysoo.ca/2009/02/14/javascript-anonymous-function-closure-and-you/