加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

Angular 2 组件之间如何通信?

发布时间:2020-12-17 09:51:06 所属栏目:安全 来源:网络整理
导读:转载自:Angular 2 组件之间如何通信? 组件之间的共享可以有好几种方式 父-子 input 方式 import { Component , Input } from ' angular2/core ' ;@ Component ({ selector : ' child ' ,template ` h2child {{content}}/h2 ` }) class Child { @ Input ()

转载自:Angular 2 组件之间如何通信?

组件之间的共享可以有好几种方式

父->子 input 方式

import {Component,Input} from 'angular2/core';
@Component({
    selector: 'child',template`
        <h2>child {{content}}</h2>
    `
})
class Child {
    @Input() content:string;
}

@'App',directives: [Child],145)">        <h1>App</h1>
        <child [content]="i"></child>
export App {

    i:number = 0;

    constructor() {
        setInterval(()=> {
            this.i++;
        },1000)
    }

}

子->父 output 方式

import {Output,EventEmitter,Component} 'angular2/core'; @ <h2>child</h2> Output() updateNumberI:EventEmitter<number> = new EventEmitter(); ithis.updateNumberI.emit(++this.i); },179)">1000) } } @ <h1>App {{i}}</h1> <child (updateNumberI)="numberIChange($event)"></child> numberIChange(i:number){ this.i = i; } }

子获得父实例

如果不了解forwardRef用处的的可以看#11
@Host表示这个Injector必须是host element在这里可以理解为parent

import {Host,Component,forwardRef} Child { constructor(@Host() @Inject(forwardRef(()=> App)) app:App) { => { app.i1000); } } @ <child></child> App { i0; }

父获得子实例

子元素指令在父constructor时是获取不到的,所以必须在组件的ngAfterViewInit生命周期钩子后才能获取,如果对组件生命周期不了解的话,可以参考#56

import {ViewChild,145)"> <h2>child {{i}}</h2> Child { i0; } @App { @ViewChild(Child) child:Child; ngAfterViewInit() { this.child.i service 方式
Injectable} Injectable(); KittencupService { i <h2>child {{service.i}}</h2> constructor(public service:KittencupService){ } } @: [KittencupService],163)">App { constructor(service:KittencupService) { => { service.i service EventEmitter方式
Injectable,EventEmitter} Injectable() KittencupService { change: EventEmitter>; constructor(){ this.change EventEmitter(); } } @<h2>child {{i}}</h2> ` }) Child { public i:KittencupService){ service.change.subscribe((value:number)=>{ = value; }) } } @<h1>App {{i}}</h1> <child></child> => { service.change.1000) } }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读