AngularJS 2 组件交换体式格局

以下的测试例子都可以在 github 找到,然则近来彷佛不太稳固。

实在 ng2 在这方面做得挺好的,用起来也很简朴,所以看完基础就可以动手写一写。壮大并不止是这一方面,在写这些的过程当中,经由过程一些设置,让开辟很地道,有时间再录一个新手入门的开辟教程。

(1) 父组件向子组件流入数据

这类体式格局是最简朴的,在 ng2 中处置惩罚得异常圆满,经由过程在子组件中标记 @Input() 输入接口的体式格局举行吸收父组件的值,我下面的 demo 重要分了几种场景,尽量的多掩盖差别状况吧。

基础上例子中掩盖了罕见的状况:

  • 直接传入一个字符串的状况,不须要绑定父组件的一个变量

  • 绑定父组件变量的状况,然后可以在父组件中不停修正

  • 输入别号的状况,可以在子组件中对输入的变量名举行从新设置

  • ngOnChanges() 在子组件中监听属性的修正

  • 特别状况下,我们须要对父组件传入的数据举行过滤

  • @ViewChild() 注解的跨多层子组件的视察体式格局

说了这么多,来看一下现实的代码吧。


// Parent component
import { Component, OnInit } from '@angular/core';
    
@Component({
    selector: 'app-parent',
    templateUrl: './parent.component.html',
    styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
    
    baby: string = '你的名字';
    
    constructor() { }
    
    ngOnInit() {
    }
    
}

// Parent html
<h3>请输入 Baby 的名字:</h3>
<input [(ngModel)]="baby" type="text"> 
<app-child babyName="hello" [inputBabyName]="baby" aliasBabyName="我是别号"></app-child>
    

// Child component
import { Component, OnInit, Input, SimpleChange } from '@angular/core';

@Component({
    selector: 'app-child',
    templateUrl: './child.component.html',
    styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
    
    @Input() babyName: string;
    @Input() inputBabyName: string;
    @Input('aliasBabyName') aliasName: string;
    
    changes: string;
    
    constructor() { }
    
    ngOnInit() {
    }
    
    ngOnChanges(changes: SimpleChange) {
        this.changes = JSON.stringify(changes);
    }
}

// Child html
<h3>我是子组件的属性(babyName) => {{babyName}}</h3>
<h3 style="color:red;">我是跟父组件来:{{inputBabyName}}</h3>
<h3>我是 aliasBabyName => aliasName:{{aliasName}}</h3>

那末我须要过滤一下值要怎样弄呢?

如许我们就可以用到 setter 和 getter 的特征来做,细致以下:


// Child component
_filterName: string = '';
    
@Input()
set filterName(n: string) {
    this._filterName = n + 'wowo~~~';
}
    
get filterName() {
    return this._filterName;
}

// Parent html
<app-child [filterName]="babyName"></app-child>

这个实在也是用 @Input() 这个注解来做的,有点相似 computed 的观点吧,然则如许做关于习气 Java 的小伙伴是很友爱的,实在经由过程一些权限的设置,还可以越发的壮大。

@ViewChild() 的体式格局

这类体式格局我以为更多的是,我的沟通逻辑存在于 TS 中的时刻就很有用。并且是描述性的定义体式格局,所以逻辑也是清楚的。


// Parent component
// 体式格局1,定义了 `#` 的钩子也是可以援用的
@ViewChild('child') cc: ChildComponent;
    
// 直接视察某一个子组件
@ViewChild(ChildComponent)
cc_other: ChildComponent;
    
// 挪用的时刻
this.cc.name = '变身啦!超等赛亚人';
this.cc_other.name = '变身啦!超等赛亚人 4';

可以思索一下,是不是任何情势的父组件流入子组件的体式格局,都可以触发 ngOnChanges() 要领。

(2) 子组件向父组件通讯

从软件的构造上来讲,是上层笼统对底层的细致实现是隐蔽的,所以细致层的东西最好尽量少的晓得笼统层的事变,或许表达体式格局不一样,然则如许的话封闭性会好许多,更多的暴露是以某一个权限开放的接口情势。然则通讯是很庞杂的东西,就彷佛人与人之间的联络是一样的。好吧,我们来细致说一会儿组件怎样接见父组件。重要经由过程的体式格局是:

  • 在子组件定义一个 @Output()EventEmitter<T> 对象,这个对象可所以 Subject 的情势存在,也就是可以运用 RxJS 的思想来做,个中 T 范型示意定义须要传入的数据细致范例。

  • 父组件中定义一个本身的函数来修正本身的信息,或许再传入其他子组件运用。


// Parent component
import { Component, OnInit } from '@angular/core';
    
@Component({
    selector: 'app-parent',
    templateUrl: './parent.component.html',
    styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
    
    babyName: string;
    
    constructor() { }
    
    ngOnInit() {
    this.babyName = '小撸一号';
    }
    
    changeBabyName(newBabyName) {
        this.babyName = newBabyName;
    }
 
}

// Parent html
<h3>BabyName:{{babyName}}</h3>
<app-child (changeBabyName)="changeBabyName($event)"></app-child>

import { Component, OnInit, Output, EventEmitter } from '@angular/core';
    
@Component({
    selector: 'app-child',
    templateUrl: './child.component.html',
    styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
    
    @Output()
    changeBabyName: EventEmitter<string> = new EventEmitter<string>();
    
    rhashcode = /\d\.\d{4}/;
    
    constructor() { }
    
    ngOnInit() {
    }
    
    getNewBabyName(e) {
        let newName = this.makeHashCode('小撸新号');
        this.changeBabyName.next(newName);
    }
    
    /* UUID http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript */
    makeHashCode(prefix) {
        prefix = prefix || '60sky';
        return String(Math.random() + Math.random()).replace(this.rhashcode, prefix);
    }
}

<button (click)="getNewBabyName($event)">我要改我本身的名字</button>

个中须要注重的是父组件中要领注入的 $event 对象,这个对象在这里注入的是子组件传入的值,所以在父组件中就可以直接运用了,我这里定义了 string 范例的数据,所以传入后定义接口的参数范例也是相对应的。

(3) 无关组件的通讯

ng2 在无关组件的处置惩罚上,真的处置惩罚得很痛快,给你一个钩子,你用吧!就是这类简朴的思绪。这里我只引见部份,由于官方文档有越发细致的引见,不然我这篇文章就写得太长了~由于体式格局有许多种,发挥小聪明就可以发明许多。

  • 事宜回调传来传去的体式格局

  • Service 的注入

  • # 钩子的体式格局

这里引见的是一个 # 钩子的体式格局来做,直接来代码吧,很轻易的。
个中,须要注重的是作用域的断绝,子组件可以很好的断绝作用域。


// Parent component
import { Component, OnInit } from '@angular/core';
    
@Component({
    selector: 'app-parent',
    templateUrl: './parent.component.html',
    styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
    
    babyName: string = '小撸一号';
    
    constructor() { }
    
    ngOnInit() {
    }
    
}

// Parent html
<input [(ngModel)]="babyName" type="text">
    
<app-child #child [childName]="babyName"></app-child>
<app-otherChild helloBaby="child.childName"></app-otherChild>

// Child component
import { Component, OnInit, Input } from '@angular/core';
    
@Component({
    selector: 'app-child',
    templateUrl: './child.component.html',
    styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
    
    @Input() childName: string;
    
    constructor() { }
    
    ngOnInit() {
    }
    
}

<h3 style="color:red;">Child:{{childName}}</h3>

// OtherChild component
import { Component, OnInit, Input } from '@angular/core';
    
@Component({
    selector: 'app-otherChild',
    templateUrl: './otherChild.component.html',
    styleUrls: ['./otherChild.component.css']
})
export class OtherChildComponent implements OnInit {
    
    @Input() helloBaby: string;
    
    constructor() { }
    
    ngOnInit() {
    }
    
    changeChildName(e) {
        this.helloBaby = '小撸新号';
    }
}

// OtherChild html
<h3 style="color:blue;">otherChild:{{helloBaby}}</h3>
<button (click)="changeChildName($event)">我来一致修正一下</button>

实在另有一些体式格局和特别场景下的处置惩罚,所以整体来讲,ng2 在这方面是不错的~

    原文作者:小撸
    原文地址: https://segmentfault.com/a/1190000007791206
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞