Javascript 角度2:如何将属性传递给子组件?

Javascript 角度2:如何将属性传递给子组件?,javascript,angular,angular2-directives,Javascript,Angular,Angular2 Directives,在我的应用程序中,Home是根组件,另一个通用组件名为list,我在Home中呈现它 我想将数据作为属性传递给来自XMLHttpRequest的列表组件 home.ts import {Component} from 'angular2/core'; import {DashboardService} from '../../services/dashboard'; import {List} from '../contact/list'; @Component({ selector: '

在我的应用程序中,Home是根组件,另一个通用组件名为list,我在Home中呈现它

我想将数据作为属性传递给来自XMLHttpRequest的列表组件

home.ts

import {Component} from 'angular2/core';
import {DashboardService} from '../../services/dashboard';
import {List} from '../contact/list';

@Component({
  selector: 'home',
  template: 
     `
     <h3>Home</h3>
     <List type="{{type}}"></List>
     `
  providers: [DashboardService],
  directives: [List],
})
export class Home {

  private _type: any;

  constructor(private _dashboardService: DashboardService) {
    this._dashboardService.typeToDisplay()
      .subscribe((type) => {
          this._type = type;
      });
  }
}
@Component({
  selector: 'List',
  properties: ['type'],
  template: `
        <h2>list</h3>
  `,
  providers: [DashboardService]
})
export class List {

  private type: any;

  constructor(@Attribute('type') type:string) {
    this.type = type;
    console.log(type);
  }
}
从'angular2/core'导入{Component};
从“../../services/dashboard”导入{DashboardService};
从“../contact/List”导入{List};
@组成部分({
选择器:“主页”,
模板:
`
家
`
提供程序:[仪表板服务],
指令:[列表],
})
出口级家庭{
私有类型:任意;
构造函数(专用仪表板服务:仪表板服务){
此.\u dashboardService.typeToDisplay()
.订阅((类型)=>{
这个._type=type;
});
}
}
List.ts

import {Component} from 'angular2/core';
import {DashboardService} from '../../services/dashboard';
import {List} from '../contact/list';

@Component({
  selector: 'home',
  template: 
     `
     <h3>Home</h3>
     <List type="{{type}}"></List>
     `
  providers: [DashboardService],
  directives: [List],
})
export class Home {

  private _type: any;

  constructor(private _dashboardService: DashboardService) {
    this._dashboardService.typeToDisplay()
      .subscribe((type) => {
          this._type = type;
      });
  }
}
@Component({
  selector: 'List',
  properties: ['type'],
  template: `
        <h2>list</h3>
  `,
  providers: [DashboardService]
})
export class List {

  private type: any;

  constructor(@Attribute('type') type:string) {
    this.type = type;
    console.log(type);
  }
}
@组件({
选择器:“列表”,
属性:['type'],
模板:`
列表
`,
提供者:[仪表板服务]
})
导出类列表{
私有类型:任意;
构造函数(@Attribute('type')类型:string){
this.type=type;
console.log(类型);
}
}
我从typeToDisplay()方法获取字符串数据,它是一个Http请求&分配给type变量。但当我作为属性传递给列表组件时,我在列表构造函数中得到null

我也试过了,但我用同样的方法得到了“type”字符串

希望我的问题很清楚。

这个语法

<List type="{{type}}"></List>
而不是属性注入。

这样,该值在构造函数中还不可用,仅在
ngOnInit()
或更高版本中可用。

文档正在处理中。这项工作仍在进行中。在开发软件之前编写文档通常是行不通的;-)。还要检查源代码中的代码文档。很多类都有相当全面的文档和指向Plunker中运行示例的链接。对我来说,我不需要前缀“.attr”。感谢u@Adir
.attr
主要是必需的,您需要它在HTML中显示,或者如果它只能添加到HTML中,因为HTML元素上没有具有此名称的属性,或者该元素上没有任何角度组件或指令。
@Input() type: any;