2016-02-09 55 views
1

在聚合物I可以创建定制的聚合物元件和经由HTML设置任何其属性的,像这样如何将attirbute值从html传递给angular 2.0组件?

设置字符串属性或甚至对象。

如何在角2.0中做到这一点?

import {Component, Input, OnInit} from 'angular2/core'; 
import {Http, HTTP_PROVIDERS} from 'angular2/http'; 
import {CORE_DIRECTIVES} from 'angular2/angular2'; 
import {ItemsPipe} from './pipe'; 

@Component({ 
    selector: 'json-schema-form', 
    viewProviders: [HTTP_PROVIDERS], 
    templateUrl: 'app/json-schema-form.html', 
    pipes: [ItemsPipe], 
    inputs: [ 
     'foo:foo', 
    ] 
}) 

export class AppComponent implements OnInit{ 

    constructor(http_: Http) { 
     console.log('constructor invoked'); 
     this.http = http_; 
     console.log(this.foo); 
    } 
    ngOnInit() { 
     console.log('init invoked'); 
     console.log(this.foo); 
     this.http.get(this.foo) 
     .subscribe(resp => this.schema = resp.json()); 
    } 
    //foo = 'test-hyper-schema.json' 

    @Input() foo; 
    http = {}; 

    schema = { 
     properties: { 
      id: { 
       type: 'number', 
       title: 'Resource id', 
      } 
     }, 
    }; 
    entity = {}; 
    toInputType = function(schemaType) { 
     var mapping = { 
      string: 'text', 
      number: 'number', 
      integer: 'number', 
     }; 
     return mapping[schemaType]; 
    } 

    props = function() { 
     return Object.keys(this.schema.properties); 
    }; 
} 

这里是index.html的

<html> 
    <head> 
    <meta charset="utf-8"> 
    <meta name="viewport" content="width=device-width, initial-scale=1" > 
    <title>Angular experiments</title> 
    <script src="node_modules/es6-shim/es6-shim.min.js"></script> 
    <script src="node_modules/systemjs/dist/system-polyfills.js"></script> 

    <script src="node_modules/angular2/bundles/angular2-polyfills.js"></script> 
    <script src="node_modules/systemjs/dist/system.src.js"></script> 
    <script src="node_modules/rxjs/bundles/Rx.js"></script> 
    <script src="node_modules/angular2/bundles/angular2.dev.js"></script> 
    <script src="node_modules/angular2/bundles/http.dev.js"></script> 

    <script> 
     System.config({ 
     packages: {   
      app: { 
      format: 'register', 
      defaultExtension: 'js' 
      } 
     } 
     }); 
     System.import('app/main') 
      .then(null, console.error.bind(console)); 
    </script> 

    </head> 
    <body> 

    <json-schema-form foo="test-hyper-schema.json"> 
     Loading... 
    </json-schema-form> 

    <!--<json-schema-form >--> 
     <!--Loading...--> 
    <!--</json-schema-form>--> 

    </body> 
</html> 
+0

很多代码,但我不清楚实际问题是什么。 –

回答

2

@Input()当前不根组件(AppComponent)上工作。

+0

我会尝试把它放在另一个组件。如果这可行,我会接受你的答案。 – user1685095

+0

还有一件事。这个组件的要点是创建可重用的小部件。其他人如何使用它,如果它不能在根组件中工作? – user1685095

+0

可重复使用的Angular组件只能在其他Angular组件中使用,因此这不应该是一个问题,否则它是一个“独立”的Angular应用程序,您可以在一个页面内拥有多个组件,但这是不寻常的。 –