angular2.0父子组件通信---如何通过组件属性将数据传递给子组件

1. input properties, typically adorned with @Input decorations.

  1. import{ Component,Input} from'@angular/core';
  2. import{ Hero} from'./hero';
  3. @Component({
  4. selector:'hero-child',
  5. template:`
  6. <h3>{{hero.name}} says:</h3>
  7. <p>I, {{hero.name}}, am at your service, {{masterName}}.</p>
  8. `
  9. })
  10. exportclassHeroChildComponent{
  11. @Input() hero: Hero;
  12. @Input('master') masterName: string;
  13. //The second @Input aliases the child component property name masterName as 'master'.
  14. }
  15. 2.在父组件就可以这样使用了
    1. import{ Component} from'@angular/core';
    2. import{ HEROES }from'./hero';
    3. @Component({
    4. selector:'hero-parent',
    5. template:`
    6. <h2>{{master}} controls {{heroes.length}} heroes</h2>
    7. <hero-child *ngFor="let hero of heroes"
    8. [hero]="hero"
    9. [master]="master">
    10. </hero-child>
    11. `
    12. })
    13. exportclassHeroParentComponent{
    14. heroes= HEROES;
    15. master:string= 'Master';
    16. }
    还可以通过定义子组件存取器来跟父组件的数据交互哦:
  16. 1.
    1. import { Component, Input } from '@angular/core';
    2. @Component({
    3. selector: 'name-child',
    4. template: '<h3>"{{name}}"</h3>'
    5. })
    6. export class NameChildComponent {
    7. private _name = '';
    8. @Input()
    9. set name(name: string) {
    10. this._name = (name && name.trim()) || '<no name set>';
    11. }
    12. get name(): string { return this._name; }
    13. }
    2.
    1. import { Component } from '@angular/core';
    2. @Component({
    3. selector: 'name-parent',
    4. template: `
    5. <h2>Master controls {{names.length}} names</h2>
    6. <name-child *ngFor="let name of names" [name]="name"></name-child>
    7. `
    8. })
    9. export class NameParentComponent {
    10. // Displays 'Mr. IQ', '<no name set>', 'Bombasto'
    11. names = ['Mr. IQ', ' ', ' Bombasto '];
    12. }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值