2016-09-19 85 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; 
}