帝王谷资源网 Design By www.wdxyy.com
对于angular2中的Input和Output可以和AngularJS中指令作类比。
Input相当于指令的值绑定,无论是单向的(@)还是双向的(=)。都是将父作用域的值“输入”到子作用域中,然后子作用域进行相关处理。
Output相当于指令的方法绑定,子作用域触发事件执行响应函数,而响应函数方法体则位于父作用域中,相当于将事件“输出到”父作用域中,在父作用域中处理。
看个angular2示例吧,我们定义一个子组件,获取父作用域的数组值并以列表形式显示,然后当点击子组件的元素时调用父组件的方法将该元素删除。
//app.component.html <app-child [values]="data" (childEvent) = "getChildEvent($event)"> </app-child> //app.component.ts @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { data = [1,2,3]; getChildEvent(index){ console.log(index); this.data.splice(index,1); } }
以上是跟组件app-root的组件类及模板,可以我们把data输入到子组件app-child中,然后接收childEvent事件并对其进行响应。
//app-child.component.html <p *ngFor="let item of values; let i = index" (click)="fireChildEvent(i)"> {{item}} </p> //app-child.component.ts @Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.css'] }) export class ChildComponent implements OnInit { @Input() values; @Output() childEvent = new EventEmitter<any>(); constructor() { } ngOnInit() { } fireChildEvent(index){ this.childEvent.emit(index); } }
子组件定义了values接收了父组件的输入,这里就是data值,然后使用ngFor指令显示。
当点击每个元素的时候触发了click事件,执行fireChildEvent函数,该函数要将元素的index值“输出”到父组件中进行处理。
Output一般都是一个EventEmitter的实例,使用实例的emit方法将参数emit到父组件中,触发父组件的childEvent事件。
然后父组件监听到该事件的发生,执行对应的处理函数getChildEvent,删除传递的元素索引指向的数据,同时,视图更新。
实际效果:
源码地址:https://github.com/justforuse/angular2-demo/tree/master/angular-input-output
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
帝王谷资源网 Design By www.wdxyy.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
帝王谷资源网 Design By www.wdxyy.com
暂无评论...
更新日志
2024年10月25日
2024年10月25日
- 群星2013-青春缤纷辑压箱宝大公开3CD2[新加坡限量版][WAV整轨]
- 林育群.2013-BalladShow(日本版)【环球】【WAV+CUE】
- 陈加洛.1992-痛到感觉不到【宝丽金】【WAV+CUE】
- 群星.2023-宿命之敌电视剧原声带【韶愔音乐】【FLAC分轨】
- 東京事変-大発見[FLAC+CUE]
- 椎名林檎-三文ゴシップ[FLAC+CUE]
- 2024年08月04日
- 裘德《裘德「最后的水族馆」演唱会LIVE》[320K/MP3][228.89MB]
- 裘德《裘德「最后的水族馆」演唱会LIVE》[24bit 48kHz][FLAC/分轨][2.08G]
- 基因三重奏《如果你什么都不说 音乐会现场录音》[320K/MP3][145.37MB]
- 孟庭苇.1996-月亮说话(2020环球24KGOLD限量版)【上华】【WAV+CUE】
- 群星.1997-新艺宝优质音响系列·国语精选监听版【新艺宝】【WAV+CUE】
- 阿桑.2005-寂寞在唱歌(星外星引进版)【华研国际】【WAV+CUE】
- 基因三重奏《如果你什么都不说 音乐会现场录音》[FLAC/分轨][287.43MB]
- 蔡题谦《我爱你,却依然要看你走》[320K/MP3][88.65MB]