好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

angular5 组件通信(一)

  用了两年angular1,对1的组件通信比较熟练,最直接的就是直接使用scope的父子节点scope就可以实现,且基本都是基于作用域实现的通信;还有就是emit,broadcast,on这几个东西了。但是到了angular2,就不再有作用域这个概念了,那么,angular2以后,组件的通信是什么样的呢?

  主要是父子组件的通信,angular5使用的是@Input来实现父传子,通过@Output和EventEmitter来实现子传父。由此可见其单向数据绑定思想,对于提升效率有很大作用。而父子互传,则又相当于1的双向数据绑定。

  上代码解析:

// child-component.ts
import { OnInit, Component, Input } from \'@angular/core\';

@Component({
    selector: \'child-component\',
    ...
})
export class ChildComponent implements OnInit {
    @Input
    count: number = 0;

    ngOnInit() {
        console.log(this.count);    // 父组件内传入的值或者我们自己设置的初始值0
    }

    increaseNumber() {
        this.count ++;
    }

    descreaseNumber() {
        this.count --;
    }
}

  

// father-component.ts
import { Component } from \'@angular/core\';
import { ChildComponent } from \'child-component/child-component\';

@Component({
    template: `
        <child-component [count]=\'initialCount\'></child-component>
    `,
    ...
})
export class FatherComponent {
    initialCount: number = 5;
}

  至此则实现了父传[count]=\'initialCount\'到子的通信。

  我们给父组件增加一个事件接收子组件发来的消息,并且在子组件需要发送的地方进行发送。

// father-component.ts
import { Component } from \'@angular/core\';
import { ChildComponent } from \'child-component/child-component\';

@Component({
    template: `
        <child-component [count]=\'initialCount\' (change)="countChange($event)"></child-component>
    `,
    ...
})
export class FatherComponent {
    initialCount: number = 5;

    countChange($event) {

    }
}

  

// child-component.ts
import { Component, Input, Output, EventEmitter } from \'@angular/core\';

@Component({
    selector: \'child-component\',
    ...
})
export class ChildComponent {
    @Input
    count: number = 0;

    @Output
    change = new EventEmitter();

    increaseNumber() {
        this.count ++;
        this.change.emit(this.count);
    }

    descreaseNumber() {
        this.count --;
        this.change.emit(this.count);
    }
}

  至此实现父子双向通信。

  而在angular中,双向绑定有独特的写法,即[()],如上边的child-component就可以写作

<child-component [(count)]=\'initialCount\'></child-component>

  即:双向数据绑定 = 单向数据绑定 + 事件  的思想。

< input type= \'text\' name= \'userName\' [( ngModel)]= "userName">

等价于

< input type= \'text\' name= \'userName\' [ ngModel]= "userName" ( ngModelChange)= "userName=$event">


除此之外,还有通过service,消息定义subscribe,父子互相获取实例这几种方法来实现。见
https://www.cnblogs.com/huangenai/p/7246651.html
https://blog.csdn.net/qq_15096707/article/details/52859110

查看更多关于angular5 组件通信(一)的详细内容...

  阅读:33次