写点什么

Angular2 组件间的数据传递,这几种姿势你知道吗(一)

  • 2020-01-07
  • 本文字数:1167 字

    阅读完需:约 4 分钟

Angular2组件间的数据传递,这几种姿势你知道吗(一)

组件间的数据传递方式有很多,这里只介绍几种常用场景下的数据传递方式,以方便初学者学习理解一点组件间数据传递的知识,若有不准确之处,欢迎指正,大神请轻喷,废话不多说了,开整!

1. 父组件到子组件的数据传递

父组件向子组件数据传递的最简便的方式是通过子组件的输入属性流入子组件,并在子组件中完成拦截接收,从而实现由外到内的数据传递(@Input 输入属性在这里就不多做介绍,它在父到子组件的作用,如下图,像探针一样获取数据并传递到子组件内部)


下面我们先看下示例:



父组件准备


首先在父组件(app-root)中定义需要传递的数据如示例中的 showNum ,然后将数据与子组件的 value 进行绑定,如下代码所示


//app.component.html
<div style="text-align:center" > <h1> Welcome to {{ title }}! <br/><button (click)="children.fn()">通过#children获取子组件的方法</button><br/><button (click)="onclick()">通过@viewChild获取子组件的方法</button><content #children></content> <square [value]="showNum"></square> <broad [options]="broadNum" (onCollect)='collectNum($event)'></broad> </h1></div>
//app.component.tsimport { Component,ViewChild } from '@angular/core';import { ContentComponent } from './component/content.component/content.component';@Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { @ViewChild(ContentComponent) child: ContentComponent; title = 'app'; broadNum = [0,1,2,3,4,5,6,7,8]; showNum = '1'; collectNum(num){ this.showNum = num; } onclick(){ this.child.fn(); }}
复制代码

子组件接收

然后在子组件中通过 @input 装饰器来获取 value,然后在组件数据 change 回调中将 value 值更新到子组件的视图,完成一次父组件到子组件的数据传递(说明:本示例中使用 ngOnChanges 监听数据变化更新视图,你也可以使用 setter 拦截输入属性实现数据的拦截)


//square.component.html<button class="square"> {{square.value}}</button>
// square.component.tsimport { Component,Input,OnInit,OnChanges,SimpleChanges} from '@angular/core';@Component({ selector: 'square', templateUrl: './square.component.html', styleUrls: ['./square.component.css']})export class SquareComponent implements OnInit, OnChanges{ square:object = { value:'12' }; @Input() value:string; ngOnChanges(changes: SimpleChanges) { // 外部修改show属性的处理,初始定义在ngOnInit中处理 if (changes['value']) { this.square.value = this.value } }}
复制代码


本转载自 Think 体验设计公众号。


原文链接:https://mp.weixin.qq.com/s/QBYWSVi0DDKKNf1GLC5sTw


2020-01-07 17:54636

评论

发布
暂无评论
发现更多内容
Angular2组件间的数据传递,这几种姿势你知道吗(一)_文化 & 方法_Think体验设计_InfoQ精选文章