Angular2 diving in components ;-)
Home Home Contact us Contact
home News Projects Tests Files Follow manatlan on Twitter Sign in
back 2015-10-19 11:14:38

Angular2 diving in components ;-)

Here is a standalone file, which is fully executable in any browser (and ready to be hacked). It's typically the kind of example I dreamed to find at the beginning of my diving. But resources are, on the web, a huge soup of different versions. But remember : angular is in alpha ;-)

This example expose some concepts:

  • use of ES5 (classic javascript), cause I did't want to fight with all others concepts, to focus on a2 only ;-)
  • a custom pipe
  • Parent & nested child components
  • Share infos to child thru properties and content (transclude)
  • a custom event (to notify parent from a child event)
  • an external service (auto-injected), to deal with datas (model).

Hope it could help someone.

<html>
  <head>
    <script src="https://code.angularjs.org/2.0.0-alpha.44/angular2.sfx.dev.js"></script>
  </head>
  <body>
        <app/>
  </body>

  <script>
    function MyService() {
      var liste=[];
      return {
        all:function()    { return liste.slice(0) },
        add:function(x)   { liste.push(x) },
        sub:function(idx) { liste.splice(idx,1) },
      }
    }

    var MyPipe = ng
        .Pipe({name:"mypipe"})
        .Class({
          constructor: function () {},
          transform(val) { return "**"+val+"**";}
        });

    var ItemComponent = ng
        .Component({
          selector: 'item',
          properties: ["index"],
          events:["deleteme"],
        })
        .View({
          template: `
              <div>
                {{index}} ) <ng-content></ng-content>
                 <button (click)='onDeleteme($event)'>X</button>
              </div>

            `,
          directives: [ng.CORE_DIRECTIVES],
        })
        .Class({
          constructor: function () {
            this.deleteme = new ng.EventEmitter();
          },
          onDeleteme:function(event) {
            this.deleteme.next();
          }
        });


    var AppComponent = ng
        .Component({
          selector: 'app',
          bindings : [MyService],
        })
        .View({
          template: `
              <input #name/> <button (click)='mys.add(name.value)'>Add</button>
              <div *ng-for='#i of mys.all(); var index=index'>
                  <item [index]="index + 1" (deleteme)="mys.sub(index)">{{i | mypipe}}</item>
              </div>
            `,
          directives: [ng.CORE_DIRECTIVES,ItemComponent],
          pipes: [MyPipe]
        })
        .Class({
          constructor: [MyService, function (mys) {
            this.mys=mys;
          }],
        });

    ng.bootstrap(AppComponent);
  </script>
</html>

Tags: angular
RSS Python Powered Get Ubuntu
©opyleft 2008-2017 - manatlan