[转]Angular2-组件间数据传递的两种方式

本文转自:https://www.cnblogs.com/longhx/p/6960288.html

Angular2组件间数据传递有多种方式,其中最常用的有两种,一种是配置元数据(或者标签装饰),一种是用单例模块传递;有两个元数据具有传递数据的功能:inputs和outputs。

一、元数据传递

  1)配置inputs,接收外部传来的参数

  在inputs里配置输入属性,宿主同过这个属性就能把数据传进来。

  示例如下:

复制代码
@Component({
selector: 'test-component',
template: `{{inputValue}}`,
inputs: ['inputsValue'] 
})
export class TestComponent {
private inputsValue;//注意,要在组建内声明,才能使用
}
复制代码

  宿主通过“[输入属性]=输入值”的方式传值,给属性打上中括号代表输入。以上面例子为例,其父组件调用方式如下:

复制代码
@Component({
selector: 'parent-component',
template: `<test-component [inputsValue]="data"></test-component>`//以“[属性]=值”的方式传递
})
export class ParentComponent {
  private data = 'Hello InputValue~!';
}
复制代码

  当然,如果不配置元数据,我们还可以在组件类中用“@Inputs() inputsValue”声明,效果一样;我们还可以编写“setter”函数对输入的数据进行加工过滤,这里不做细讲。

  2)配置outputs,给父组件传递数据

  outputs是利用自定义事件的机制给父组件传递数据;元数据配置与inputs相似,只是组件类中要给输出属性创建EventEmitter实例。

  示例如下:

复制代码
@Component({
  selector: 'test-component',
  template: `<button (click)="clickToSend()">点击按钮,输出数据</button>`,
  outputs: '[outputValue]'
})
export class TestComponent {
  public outputValue = new EventEmmitter;
  private clickToSend() {
    this.outputValue.emit('Hello OutputValue~!');//注意,自定义事件必须要借助异步程序执行发布函数;异步程序有事件、前后端数据交互、延时函数。
  }
}
复制代码

  outputs相当于给组件声明了一个自定义事件,父组件绑定该事件就能与输出机制建立联系,输出数据就是事件对象。

  以上面例子为例,父组件示例如下:

复制代码
@Component({
  selector: 'parent-component',
  template: `<test-component (outputValue)="getValue($event)"></test-component>`//属性加上小括号代表输出
})
export class ParentComponent {
  private getValue(event) {
    console.log(event);//Hello OutputValue~!
  } 
}
复制代码

  同样,你也可以用@Output来声明,这里不做细讲。

 

二、单例模块传递

  JavaScript传值策略是:基本类型数据传数据副本,对象类型数据传对象引用。Angular2各模块注入Module中,只要在Module作用域范围,这些模块再通过依赖注入方式注入到别的模块,依赖的模块是单例的。

  我们可以利用对象传引用的特性,达到组件间传递数据的目的。

  比如我想将数据传给子组件,只需在子组件构造器中注入该组件,该组件由于是单例的,那么一方改动另一方能实时访问到。

  示例如下:

复制代码
//父组件:
@Component({
  selector: 'parent-component',
  template: `
    <p>{{value}}</p>
    <child-component></child-component>
  ` 
})
export class ParentComponent {
  public value = 'Parent Value...';//注意!这里不能使用private权限,否则外部模块无法访问到这个属性。
}

//子组件:
@Component({
  selector: 'child-component',
  template: `{{_parent.value}}`
})
export class ChildComponent {
  constructor(private _parent: ParentComponent) {}//注入父组件的实例,就能访问到父组件非私有属性了。
}
复制代码

  结果是<p>Parent Value...</p><child-component>Parent Value...</child-component>

  你还可以用指令、管道、服务来传值,只要是单例模块,都能做到;不过为了代码内聚性,建议只使用组件或者服务作为值传递的媒介。

 

还有别的传值方式吗?

  当然还有,比如绕过Angular2的API,使用JQuery的data函数进行值的获取和传递。不建议这么做,Angular不鼓励开发者直接操作DOM,它内置了一系列指令以及机制来弱化开发者对DOM的直接操作,开发者使用Angular提供的API可以减少很多操作DOM的代码。

posted on 2018-09-16 17:52  freeliver54  阅读(670)  评论(0编辑  收藏  举报

导航