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

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

1、元数据传递

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

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

  示例以下:this

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

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

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

  固然,若是不配置元数据,咱们还能够在组件类中用“@Inputs() inputsValue”声明,效果同样;咱们还能够编写“setter”函数对输入的数据进行加工过滤,这里不作细讲。code

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

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

  示例以下:blog

@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来声明,这里不作细讲。

 

2、单例模块传递

  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的代码。

相关文章
相关标签/搜索