2016-01-16 1 views
14

Desidero specificare una proprietà Input per il mio componente utilizzando JS normale (non dattiloscritto).Angular2 Come definire la proprietà di input in Plain JS

L'unica documentazione che posso trovare è questo (che è dalla Angular2 cheat sheet):

ng.core.Input(myProperty, myComponent); 
//Declares an input property that we can 
//update via property binding (e.g. <my-cmp [my-property]="someExpression">). 

Ho provato questo nel costruttore di mia componente:

.Class({ 
    constructor: function() {  
     ng.core.Input(this.name, this);   
    } 
});  

Tuttavia, non è così lavoro (non vengono segnalati errori).

Cosa sto sbagliando?

risposta

20

Per questi casi si dispone delle proprietà inputs e outputs. Si noti che per il caso TS le annotazioni sono singolari (Input e Output) e con JS normale sono plurali (inputs e outputs).

var Children = ng.core. 
    Component({ 
    inputs : ['myValue'], // Equivalent to @Input('myValue') 
    outputs : ['emitValue'] // Equivalent to @Output() emitValue; 
    }). 
    Class({ 
    constructor: function() { 
     // Initialize emitValue 
     this.emitValue = new ng.core.EventEmitter(); 
    }, 

    // Available at ngOnInit lifecycle 
    ngOnInit : function() { 
     console.log(this.myValue); 
    }, 

    // Value that the component will emit 
    emit : function() { 
     this.emitValue.emit('This is some value from children'); 
    } 
    }); 

Con inputs è possibile utilizzare la sintassi [internalValue: externalValue], che fondamentalmente si darebbe la possibilità di fare questo

<another-cmp [externalValue]="someExpression"></another-cmp> 

.Component({ 
    inputs : ['internalValue: externalValue'] 
}) 
.Class({ 
    ngOnInit : function() { 

    // 'internalValue' contains 'externalValue' value 
    console.log(this.internalValue); 
    } 
}) 

E per il componente principale

var Parent = ng.core. 
    Component({ 
     selector: 'cmp', 
     template : ` 
      <another-cmp [myValue]="myValue" (emitValue)="printValue($event)"> 
      </another-cmp> 
      What does my children have to say? {{childrenValue}} 
     `, 
     directives : [Children] 
    }). 
    Class({ 
     constructor: function() { 
      this.myValue = 'Some value to pass to children'; 
     }, 
     printValue : function(value) { 
      this.childrenValue = value; 
     } 
}); 

Ecco un plnkr dimostrare la Astuccio. Spero possa essere d'aiuto.

+0

Funziona perfettamente, ottima spiegazione! – pixelbits

+0

fantastico! grazie! Mi chiedo dove sapere queste informazioni, se non ci sono documenti per JS. – eagor

+0

Hmm .. Non riesco a farlo funzionare e l'esempio Plunker lancia "ECCEZIONE: RangeError: Dimensione massima dello stack di chiamate superata" in Chromium 53. Sto cercando di adattare https://angular.io/docs/ts/ ultimo/tutorial/toh-pt3.html a ES2015 – dotnetCarpenter