帝王谷资源网 Design By www.wdxyy.com
学过Angular的同学都知道,输入框通过[(ngModel)]
实现双向数据绑定,那么自定义组件能不能实现双向数据绑定呢?答案是肯定的。
Angular中,我们常常需要通过方括号[]
和圆括号()
实现组件间的交互:
那么在[]
和()
的基础上,如何实现组件的双向数据绑定?
例子如下。
子组件:
<!--testDataBinding.component.html--> <h1>childStatus: {{childStatus}}</h1>
//testDataBinding.component.ts export class TestDataBindingComponent implements OnInit{ @Input() childStatus; @Output() childStatusChange = new EventEmitter(); ngOnInit(){ setTimeout(()=>{ this.childStatus = false; this.childStatusChange.emit(this.childStatus); },5000); } }
注意这里的写法,这是关键所在,输出属性前半部分必须与输入属性相同,输入属性可以随意取名,输出属性需在输入属性基础上加上Change,比如你的输入属性是myData,那么输出属性就必须是myDataChange。
父组件:
<!--app.component.html--> <test-binding [(childStatus)]="parentStatus"></test-binding> <h1>parentStatus: {{parentStatus}}</h1>
//app.component.ts import { Component,OnInit } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit{ parentStatus: boolean = true; ngOnInit(){ setTimeout(()=>{ this.parentStatus = true; },10000); } }
在父组件我们初始化parentStatus
为true
,并把它传到子组件TestDataBindingComponent
。
在子组件里,5秒后我们把childStatus
设为false
,看它能不能传到父组件。再过5秒,我们在父组件将parentStatus
设为true
,看它能不能传到子组件。
事实证明,子组件值变化后,父组件的值也跟着变化;父组件值变化后子组件的值也跟着变了!
我们实现了双向绑定!
查看本文代码和效果,可点击这里。
以上这篇Angular自定义组件实现数据双向数据绑定的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
帝王谷资源网 Design By www.wdxyy.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
帝王谷资源网 Design By www.wdxyy.com
暂无评论...
更新日志
2024年10月28日
2024年10月28日
- 群星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]