Angular:实现组件间双向数据绑定

学过Angular的同窗都知道,输入框经过[(ngModel)]实现双向数据绑定,那么父子组件间能不能实现双向数据绑定呢?答案是确定的。
Angular中,咱们经常须要经过方括号[]和圆括号()实现组件间的交互:
css

那么在[]()的基础上,如何实现组件的双向数据绑定?
例子以下。
子组件:html

<!--child.component.html-->

<h1>status in child: {{childStatus}}</h1>
<button (click)="toggle()">Toggle childStatus</button>
//child.component.ts

export class ChildComponent implements OnInit{
  @Input() childStatus;
  @Output() childStatusChange = new EventEmitter();
  ngOnInit(){
    
  }
  toggle(){
        this.childStatus = !this.childStatus;
        this.childStatusChange.emit(this.childStatus);
  }
}

注意这里的写法,这是关键所在,输出属性必须在输入属性的基础上加上‘-Change’后缀。好比你的输入属性是myData,那么输出属性就必须是myDataChangeapp

父组件:this

<!--app.component.html-->

<test-binding [(childStatus)]="parentStatus"></test-binding>

<h1>status in parent: {{parentStatus}}</h1>
<button (click)="toggle()">Toggle parentStatus</button>
//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(){
    
  }
  toggle(){
    this.parentStatus = !this.parentStatus;
  }
}

在父组件咱们初始化parentStatustrue,并把它传到子组件ChildComponent
在子组件里,经过按钮咱们能够改变childStatus的值,能够看到,子组件中的值改变的同时,父组件的值也跟着改变了。反过来,在父组件中经过按钮改变parentStatus的值,子组件中的值一样也跟着变化:code

很简单对不对?!
你能够在这里查看和在线编辑本文代码,并实时查看效果!component

相关文章
相关标签/搜索