angular2 父子组件之间的通信与传值

1. 父组件给子组件传值

父组件可以给子组件传值,方法或者是将整个父组件传给子组件

1. 在父组件的 ts 文件中定义一个变量

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

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {

  public title: string = '父组件传入的 title';

  public message: string = '父组件传入的 message';

  constructor() {
  }

  ngOnInit(): void {
  }

  run() {
    alert('父组件的 run()');
  }
}

2. 在父组件的 html 文件中,在引用子组件的标签中设置相关属性用来接收父组件传来的值

<p>parent works!</p>
<hr>
<app-child [title]="title" [message]="message" [run]="run" [parent]=this></app-child>

3. 子组件的 html

<p>child works!</p>
<p>父组件传来的 title -- {{title}}</p>
<p>父组件传来的 message -- {{message}}</p>
<hr>
<button (click)="parentRun()">执行父组件的方法</button>

4. 在子组件中引入 Input 模块,接收传入的值

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

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {

  /**
   * 接收父组件传来的 title
   */
  @Input()
  public title: string;

  /**
   * 接收父组件传来的 message
   */
  @Input()
  public message: string;

  /**
   * 接收父组件传来的 run()
   */
  @Input()
  public run: Function;

  /**
   * 接收整个父组件
   */
  @Input()
  public parent: any;

  constructor() {
  }

  ngOnInit(): void {
  }

  
  parentRun() {
    //调用父父组件的方法
    this.run();
  }
}

2. 子组件给父组件传值、执行子组件的方法

1. 父组件的 html

<p>parent works!</p>
<button (click)="getChildMessage()">获取子组件的 message</button>
<button (click)="runChild()">执行子组件的方法</button>

<hr>
<app-child #child></app-child>

2. 父组件的 ts – 引入 ViedChild 模块

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

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {

  @ViewChild('child')
  public child: any;


  constructor() { }

  ngOnInit(): void {
    alert(this.child.message);
  }

  getChildMessage() {
    //获取子组件的 message
    alert(this.child.message);
  }


  runChild() {
    //执行子组件的 run()
    alert(this.child.run())
  }
}

3. 子组件的 ts

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

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {

  public message: string = '子组件的 message';
  constructor() { }

  ngOnInit(): void {
  }

  run(){
    alert('子组件的 run()')
  }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值