繁体   English   中英

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

[英]Angular 2: how to pass attributes to child component?

在我的应用程序中,我将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请求并分配给类型变量。 但当我作为属性传递给列表组件时,我在List构造函数中得到null。

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

希望我的问题是明确的。

这个语法

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

设置属性而不是属性。
要设置属性,请使用其中一个

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

要么

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

如果您只想在List使用中获得值

@Input() type: any;

而不是属性注入。
这样,该值在构造函数中ngOnInit() ,仅在ngOnInit()或更高版本中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM