zoukankan      html  css  js  c++  java
  • Angular:实现组件间双向数据绑定

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

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

    <!--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,那么输出属性就必须是myDataChange

    父组件:

    <!--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的值,子组件中的值同样也跟着变化:

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

  • 相关阅读:
    Scilab5.5.2 在Centos5.11下binary安装(注:不是源码编译安装)
    《DSP using MATLAB》Problem 9.5
    Java 出现警告 不能读取AppletViewer的属性文件
    《DSP using MATLAB》Problem 9.4
    《DSP using MATLAB》Problem 9.2
    《DSP using MATLAB》Problem 8.46
    《DSP using MATLAB》Problem 8.45
    风力摆?这是不是太简单了点
    树莓派:基于物联网做的指纹打卡器
    Python之面向对象(一)
  • 原文地址:https://www.cnblogs.com/cme-kai/p/8012159.html
Copyright © 2011-2022 走看看