父子组件传值

父子组件传值

  我们这里定义    父组件为weather,子组件为header

  先是介绍一下子组件调用父组件

  1)Input调用值:

    在父组件中定义属性:

  msg = '今日天气';

    并且在html中把这个值给子组件传递过去

<app-header [msg]="msg" [run]="run"></app-header>

    子组件要使用Input接收

import { Component, OnInit } from '@angular/core';
import { Input } from '@angular/core'; //引入Input
@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
  @Input() msg; //在这里接收,这样就可以在子组件中调用msg

  constructor() {

  }

  ngOnInit() {
  }
}

    html

<h2 class="header">{{msg}}</h2>

  2)Input调用函数:

    和传值的方法一样

    在父组件中定义函数:

  run() {
    alert('执行父组件件的run方法');
  }

    并且在html中把这个方法给子组件传递过去

<app-header [run]="run"></app-header>

    子组件要使用Input接收

import { Component, OnInit } from '@angular/core';
import { Input } from '@angular/core';
@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
  @Input() run;
  constructor() {

  }

  ngOnInit() { 
  }
}

    html

<button (click)="run()">调用父组件的方法</button>

   3)Output子组件调用父组件的函数

    先在父组件定义好所需调用的函数


  data;
 showdata(e) {
    this.data = '显示' + e;
  }

    然后定义子组件

import { Component, OnInit } from '@angular/core';
import { Output, EventEmitter } from '@angular/core'; // 引入这两个库
@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
  @Output() outer = new EventEmitter();//初始化EventEmitter
  constructor() {

  }
  sendParent() {
    this.outer.emit('子组件数据');  //emit发送数据
  }
  ngOnInit() { 
  }
}

    再在子组件中写一个按钮触发sendParent()

    父组件调用子组件

<app-header (outer)="showdata($event)"></app-header>
<!-- outer 就是子组件的 EventEmitter 对象 outer,用于监听emit事件,$event就是emit的参数-->

   4)接下来介绍一下父组件调用子组件

    在父组件引入ViewChild

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

    Html中调用子组件时,给子组件起一个别名,不过最好还是用组件的名字,好记

<app-header #header></app-header>

    声明ViewChild绑定子组件,括号里面的参数要和我们起的别名一致

@ViewChild('header') header;

    这样我们就可以使用header直接使用子组件里面的东西了,比如:

  run() {
    alert(this.header.headermsg);  //调用子组件的属性
    const retu = this.header.headerFun();  //调用子组件的函数
    alert('调用子组件函数,结果:' + retu);
  }
原文地址:https://www.cnblogs.com/wskxy/p/9673667.html