2016-02-09 52 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應用程序,您可以在一個頁面內擁有多個組件,但這是不尋常的。 –