组件之间的通信(实例)

1.子获取父实例(在子组件中改变父组件变量值)

parent.html:

{{num}}

parent.ts:

export class ParentPage {

  num:number =0;

}

child.ts:

import { Component, Input, EventEmitter, Output,Host,Inject,forwardRef }from'@angular/core';

import{ParentPage} from'../parent/parent';

@Component{}

export class ChildPage {

constructor( @Host() @Inject(forwardRef(() => ParentPage)) app: ParentPage) {

        app.num = app.num + 10

    }

}

2.父获得子实例(@ViewChild)

parent.html:

{{num}}

parent.ts:

import {ViewChild, Component }from'@angular/core';

import{ChildPage}from'../child/child';

@Component({

  selector: 'page-parent',

  templateUrl: 'parent.html',

})

export class ParentPage { 

@ViewChild(ChildPage) child:ChildPage;

    ngAfterViewInit() {
       this.child.num++;

    }

}

child.html:

{{num}}

child.ts:

export class ChildPage {

    num:number =0;

}

你可能感兴趣的:(组件之间的通信(实例))