【问题标题】:Angular 2: how to pass attributes to child component?Angular 2:如何将属性传递给子组件?
【发布时间】:2016-01-21 06:41:27
【问题描述】:

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

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

希望我的问题很清楚。

【问题讨论】:

    标签: javascript angular angular2-directives


    【解决方案1】:

    这个语法

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

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

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

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

    如果您只想在 List 中使用该值,请使用

    @Input() type: any;
    

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

    【讨论】:

    • 文档正在进行中。 Angular 仍在进行中。在开发软件之前编写文档通常不会飞;-)。还要检查源代码中的代码文档。许多类都有相当全面的文档和在 Plunker 中运行示例的链接。
    • 对我来说,我不需要前缀“.attr”。谢谢你
    • @Adir .attr 主要是必须的或该元素上的指令。
    猜你喜欢
    • 2016-08-28
    • 2015-08-20
    • 2016-08-31
    • 1970-01-01
    • 2018-01-15
    • 2016-06-10
    • 2017-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多