码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-12-09 19:23:05      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:ges   数据   双向   9.png   blog   new   core   timeout   pre   

学过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);
  }
}

在父组件我们初始化parentStatustrue,并把它传到子组件TestDataBindingComponent
在子组件里,5秒后我们把childStatus设为false,看它能不能传到父组件。再过5秒,我们在父组件将parentStatus设为true,看它能不能传到子组件。

技术分享图片

事实证明,子组件值变化后,父组件的值也跟着变化;父组件值变化后子组件的值也跟着变了!
我们实现了双向绑定!
查看本文代码和效果,可点击这里

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

标签:ges   数据   双向   9.png   blog   new   core   timeout   pre   

原文地址:http://www.cnblogs.com/cme-kai/p/8012159.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!