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

时间:2022-01-23 22:04:33

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. }