angular 使用 @input、@Output 来进行父子组件之间数据的传递。

如下:

父元素:

<child-root parent_value="this is parent value" (child_emit)="test()"></child-root>

父元素标签中有一个属性是,parent_value,在子元素中可以使用该值:

<p [title]="parent_value" >this paragraph's title is from parent's(parent-root) attribute parent_value</p>

在子元素中,我们 p 标签的 title 属性绑定了父元素的 parent_value 属性,这里要注意了,

[title]="parent_value" 的意思并不是指 title 的值就是 "parent_value" 这个字符串,而是父元素中指定的 parent_value 属性的值。

这里,我们需要做的处理是,在子组件中,使用 @Input 去注解 parent_value 属性,指明这是一个来自父组件的元素。

在上面的例子中,父元素也定义了一个属性 child_emit,值是 test(),也就是说这是一个函数调用,在父元素组件中有一个 test 函数,可是我们应该怎么调用呢?我们毕竟没有 child_emit 这种事件,这时候我们就可以在子元素中触发父元素的这个 test 方法的调用。

但是首先我们先要在子元素组件中把 child_emit 使用 @Output 进行注解,然后将其值设为 new EventEmitter,当我们在子组件中去调用 child_emit 方法的时候,父元素中 child_emit 的值的方法(test)就会被调用。

源码如下:

child.component.ts

import {Component, EventEmitter, Input, Output} from "@angular/core";

@Component({
selector: 'child-root',
template: `
<p [title]="parent_value" >this paragraph's title is from parent's(parent-root) attribute parent_value</p>
<button class="btn-font-family" (click)="trigger()">点击的时候会触发父元素 example-root 的 child_emit 对应的事件</button>
`
})
export class ChildComponent { @Input()
parent_value; @Output()
child_emit = new EventEmitter(); trigger() {
this.child_emit.emit()
}
}

  

parent.component.ts

import {Component, Output} from "@angular/core";

@Component({
selector: 'example-root',
template: `
<child-root [parent_value]="parent_value" (child_emit)="test()"></child-root>
`,
})
export class ParentComponent {
@Output()
parent_value = 'value from parent'; test () {
console.log('call by emit at ' + new Date().toLocaleString())
}
}

  

完整源码:https://github.com/eleven26/angular-example/tree/master/src/input_output_example

最新文章

  1. HTTP基础05--http首部
  2. Android百分比布局支持库介绍——com.android.support:percent(转)
  3. SQL语言的组成
  4. Android之TextView------LINK的点击事件
  5. How to use STA(sql tuning advisor)
  6. Linux进程管理(-)
  7. Highcharts中如何外部修改pointStart
  8. 建立ipython集群
  9. ashMap源码阅读与解析
  10. ThinkPHP5+小程序商城 网盘视频
  11. oracle 合并多个sys_refcursor
  12. Activiti(二) springBoot2集成activiti,集成activiti在线设计器
  13. jQuery 选择城市,显示对应的即时时区时间
  14. 代码规范V1.1
  15. Error building Player: Exception: Could not start java
  16. 论坛:Error:No result defined for action cn.itcast.oa.view.action.TopicAction and result
  17. JavaScript--动态加载脚本和样式(23)
  18. 关于android im
  19. VBA_话费明细单_格式调整
  20. 有限制的最短路spfa+优先队列

热门文章

  1. XSS留言板实现
  2. Python最简编码规范
  3. Linux 深入理解inode/block/superblock
  4. node项目设置环境变量
  5. 用 Python 编写的 Python 解释器
  6. hbase Problem binding to node1/192.168.1.13:16020 : 地址已在使用
  7. 希尔排序(java实现)
  8. 团队介绍 you i
  9. 第二次c艹作业
  10. 软工实践-Alpha 冲刺 (7/10)