angularjs2中父子组件的数据传递的实例代码

2019-11-20,,,,

父到子组件之间的数据传递

父组件模板中引用子组件

 // father template: ...

  <child-item [name] = "fatherItemName" > </child-item>

//...`

其中”fatherItemName” 为父组件中的属性,[name] 为子组件的输入

在子组件中使用 @Input() name 来接受父组件传递的值

如果在接收值前需要进行一些处理,可以使用setter 拦截输入属性

_name: string = '';

@Input()

set nameStr(name: string){

_name = "father name:" + name;

}

这时的 _name 作为临时变量,作为set 和get的中转。

父组件中:

< child-item [namestr] = “fatherItemName” > 

name -> namestr

使用getter 输出

get nameStr(){ return _name; }

插值时 {{ nameStr }}

子到父组件之间的数据传递

1. 事件传值

  // father template: ...

  <child-item (childEvent) = "fatherFunction($event)"> </child-item>

  //...

   export class FatherComponent{

    fatherFunction(){

     alert('hello!');

   }

  }

子组件

  //...
  < p (click) = "clickThis"> click </ p>
  //...
  @Output() childEvent = new EventEmitter<boolean>();
  clickThis(){
  this.childEvent.emit();
  }

2.父组件通过局部变量获取子组件的引用

<child-item [name] = "fatherItemName" #name > </child-item>

子组件通过#绑定一个name的局部变量来访问子组件的属性

3.使用@ViewChild 获取子组件的引用

@ViewChild(ChildComponent) child: ChildComponent;

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持北冥有鱼。

您可能感兴趣的文章:

  • Angular 2父子组件数据传递之@Input和@Output详解(下)
  • Angular 2父子组件数据传递之@Input和@Output详解 (上)
  • Angular 2父子组件数据传递之@ViewChild获取子组件详解
  • Angular 2父子组件之间共享服务通信的实现
  • Angular 2父子组件数据传递之局部变量获取子组件其他成员
  • Angular2 父子组件数据通信实例

《angularjs2中父子组件的数据传递的实例代码.doc》

下载本文的Word格式文档,以方便收藏与打印。