源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Angular自定义组件实现数据双向数据绑定的实例

  • 时间:2022-12-12 22:20 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Angular自定义组件实现数据双向数据绑定的实例
学过Angular的同学都知道,输入框通过[code][(ngModel)][/code]实现双向数据绑定,那么自定义组件能不能实现双向数据绑定呢?答案是肯定的。 Angular中,我们常常需要通过方括号[code][][/code]和圆括号[code]()[/code]实现组件间的交互: [img]http://files.jb51.net/file_images/article/201712/201712110814532.png[/img] 那么在[code][][/code]和[code]()[/code]的基础上,如何实现组件的双向数据绑定? 例子如下。 [b]子组件:[/b]
<!--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。 [b]父组件:[/b]
<!--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);
 }
}
在父组件我们初始化[code]parentStatus[/code]为[code]true[/code],并把它传到子组件[code]TestDataBindingComponent[/code]。 在子组件里,5秒后我们把[code]childStatus[/code]设为[code]false[/code],看它能不能传到父组件。再过5秒,我们在父组件将[code]parentStatus[/code]设为[code]true[/code],看它能不能传到子组件。 [img]http://files.jb51.net/file_images/article/201712/201712110814533.gif[/img] 事实证明,子组件值变化后,父组件的值也跟着变化;父组件值变化后子组件的值也跟着变了! 我们实现了双向绑定! 查看本文代码和效果,可点击[b][url=https://stackblitz.com/edit/angular-uagcji?file=app%2Fapp.component.ts]这里[/url][/b]。 以上这篇Angular自定义组件实现数据双向数据绑定的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持编程素材网。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部