学过Angular的同学都知道,输入框通过imsun">[(ngModel)]实现双向数据绑定,那么自定义组件能不能实现双向数据绑定呢?答案是肯定的。
imsun">[]和圆括号imsun">()
实现组件间的交互:
那么在imsun">[]和imsun">()
的基础上,如何实现组件的双向数据绑定?
例子如下。
子组件:
rush:xhtml;">
childStatus: {{childStatus}}
export class TestDataBindingComponent implements OnInit{
@Input() childStatus;
@Output() childStatusChange = new EventEmitter();
ngOnInit(){
setTimeout(()=>{
this.childStatus = false;
this.childStatusChange.emit(this.childStatus);
},5000);
}
}
@Input() childStatus;
@Output() childStatusChange = new EventEmitter();
ngOnInit(){
setTimeout(()=>{
this.childStatus = false;
this.childStatusChange.emit(this.childStatus);
},5000);
}
}
注意这里的写法,这是关键所在,输出属性前半部分必须与输入属性相同,输入属性可以随意取名,输出属性需在输入属性基础上加上Change,比如你的输入属性是myData,那么输出属性就必须是myDataChange。
父组件:
rush:xhtml;">
<test-binding [(childStatus)]="parentStatus">
parentStatus: {{parentStatus}}
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);
}
}
@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);
}
}
在父组件我们初始化imsun">parentStatus为imsun">true
,并把它传到子组件imsun">TestDataBindingComponent
。
imsun">childStatus设为imsun">false
,看它能不能传到父组件。再过5秒,我们在父组件将imsun">parentStatus
设为imsun">true
,看它能不能传到子组件。
事实证明,子组件值变化后,父组件的值也跟着变化;父组件值变化后子组件的值也跟着变了!
我们实现了双向绑定!
。
以上这篇Angular自定义组件实现数据双向数据绑定的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持编程之家。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。