Angular2如何在Plain JS中定义输入属性

pix*_*its 14 angular

我想使用普通JS(而不是typescript)为我的组件指定一个Input属性.

我能找到的唯一文件就是这个(来自Angular2 备忘单):

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

我在我的组件构造函数中尝试过这个:

.Class({
   constructor: function () {    
       ng.core.Input(this.name, this);        
   }
});      
Run Code Online (Sandbox Code Playgroud)

但是,它不起作用(也没有报告错误).

我究竟做错了什么?

Eri*_*nez 20

对于这些情况,你有inputs和outputs属性.请注意,对于TS情况,注释是单数(Input和Output),而使用普通JS,它们是复数(inputs和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');
    }
  });
Run Code Online (Sandbox Code Playgroud)

有了inputs可以使用的语法[internalValue: externalValue],这基本上会给你这样做的可能性

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

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

    // 'internalValue' contains 'externalValue' value
    console.log(this.internalValue); 
  }
})
Run Code Online (Sandbox Code Playgroud)

而对于父组件

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;
        }
});
Run Code Online (Sandbox Code Playgroud)

这是一个展示案例的plnkr.我希望它有所帮助.