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

Hitesh Balar

在我的应用程序中,我有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;
      });
  }
}

List.ts

@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);
  }
}

我正在从typeToDisplay()方法获取字符串数据,这是一个Http请求并分配给type变量。但是当我将属性作为属性传递给列表组件时,列表构造器中的值为null。

我也尝试过,但是我以相同的方式得到“类型”字符串。

希望我的问题是明确的。

贡特·佐赫鲍尔(GünterZöchbauer)

这个语法

<List type="{{type}}"></List>

设置属性而不是属性。
要设置属性,请使用

<List attr.type="{{type}}"></List>

要么

<List [attr.type]="type"></List>

如果您只想List使用可用的值

@Input() type: any;

而不是属性注入。
这样,该值尚不能在构造函数中使用,只能在ngOnInit()以后使用。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章