angular父子组件通信 ,一个模块使用另一个模块的组件

父组件

1.parent.component.html

<div class="parentBox">
  <p>
    parent works!
  </p>
  <!--[]传参 ()传递方法  -->
  <app-child  #child [fromParent]="parent"  (notify)="onNotify($event)"></app-child>
</div>

2.parent.component.ts

import { AfterViewInit, Component, OnInit, ViewChild, ViewChildren } from '@angular/core';
// @viewChild   @ViewChildren 时候才需要引入
import { ChildComponent } from '../child/child.component';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
  // 自定义变量
  private parent = 'this is parent msg';
  // 通过模板变量名获取 
  @ViewChild("child") child: ChildComponent;
  @ViewChildren("child") children: ChildComponent;

  constructor() { }

  ngOnInit() {
  }
  // @ViewChild和@ViewChildren会在父组件钩子方法ngAfterViewInit调用之前赋值。
  ngAfterViewInit() {
    console.log(this.child);
    console.log(this.children);
  }
  // 父组件定义方法
 private  onNotify(data) {
    window.alert(`我是父组件的方法啊${data}`);
  }
}

子组件

1.child.component.html

<div class="childBox">
  <div >
    child works!
  </div>
  <!-- 来自父组件的数据 -->
  {{fromParent}}
  <!-- 调用父组件的方法并把‘4’传递给父组件 -->
  <button (click)="notify.emit(4)">子组件调用父组件的方法</button>
</div>

2.child.component.ts 

import { Component, OnInit ,Input, Output, EventEmitter} from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
  // 接收参数
  @Input() fromParent;
  // 调用父组件的方法
  @Output() notify = new EventEmitter();
  constructor() { }

  ngOnInit() {
  }

}

效果图:

  • @ViewChild  @ViewChildren 可查看组件的定义的变量和方法(具体看console里的内容选择使用)

另外,这里是定义了两个模块 ChildModule  ParentModule(不是单纯的组件间引用)

子模块 ChildModule

@NgModule({

imports: [

CommonModule

],

declarations: [ChildComponent], // 声明本模块有的组件

exports:[ChildComponent]  // 导出供其他模块使用的组件

})

export class ChildModule { }

父模块只需要引入ChildModule 就能使用子模块暴露的组件

不需要引入子模块的组件

import { ChildModule } from '../child/child.module';

@NgModule({

imports: [

CommonModule,

ChildModule, // 引入子模块

ParentRoutingModule

],

declarations: [ParentComponent]  // 声明本模块具有的组件

})

export class ParentModule { }

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值