2016-09-19 81 views
1

如果我的網頁具有組件選擇器,我正在使用angular2來提升多個UI模塊。我無法使用主應用程序元素,並將所有內容放入其中。然而,我想以某種方式將變量傳遞給每個組件。如何將變量傳遞到angular2中的模塊和組件

init.ts

System.import('@angular/platform-browser_dynamic').then(function(pbd) { 
    const platform = pbd.platformBrowserDynamic(); 

    // I will put all my modules information here 
    const modules = { 
     'my-app': { 
      selector: 'my-app', 
      file: 'myapp', 
      import: 'MyAppModule' 
     } 
    }; 

    // Loop through my settings object and look for modules/components to be bootstrapped if their selector exists on the current page 
    for(var module in modules) { 
     if(document.querySelectorAll(modules[module].selector).length > 0) { 
      System.import('app/modules/' + modules[module].file) 
        .then(function(m) { 
         platform.bootstrapModule(m[modules[module].import]); 
        }); 
     } 
    } 
}); 

modules/myapp.ts

import { NgModule } from '@angular/core'; 
import { BrowserModule } from '@angular/platform-browser'; 
import { MyAppComponent } from 'app/components/myapp'; 

@NgModule({ 
    imports: [ BrowserModule ], 
    declarations: [ MyAppComponent ], 
    bootstrap: [ MyAppComponent ] 
}) 
export class MyAppComponent { 
    // maybe dynamically bootstrap components here 
} 

component/myapp.ts

import { Component } from '@angular/core'; 

@Component({ 
    selector: 'my-app', 
    template: 'Hello World' 
}) 
export class MyAppComponent { 
    // or import data here 
} 

我的最後一點將在某種程度上能夠在元通屬性的組件。我嘗試過使用以前在angular2組件中工作的ElementRef,但在2.0.0中不再使用(不再是發佈候選)。

所以我有點失落。

回答

0

在component/myapp.ts中使用此代碼
@Input()裝飾器定義一組參數,可以從組件的父級傳遞參數。例如,我們可以修改Hello組件,以便名稱可以由父級提供.1

import {Component, Input} from '@angular/core'; 

@Component({ 
selector: 'hello', 
template: '<p>Hello, {{name}}</p>' 
}) 
export class Hello { 
@Input() name: string; 
} 
相關問題