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