angular-父组件给子组件传值

父组件:Home 子组件:Header

app.component.html:
<app-home></app-home>
home.component.html:
<app-header [title]="title" [msg]="msg"  //数据
[run]='run' 								 //方法
[home]='this'								 //整个父组件
></app-header>
<br>
<hr>
<div>我是一个home组件</div>
home.component.ts:
import { Component, OnInit} from '@angular/core';

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

  public title:any="首页组件的标题";

  public msg:any="我是父组件的msg";

  run(){
    alert('我是父组件的run方法')
  }
  constructor() { }

  ngOnInit() {
  }
}
header.component.html:
<header>{{title}}-----{{msg}}</header>

<br>

<button (click)="getParentMsg()">子组件里面获取父组件传入的msg </button>

<br>

<button (click)="getParentRun()">子组件里面执行父组件的run方法</button>

header.component.ts:
import { Component, OnInit,Input } from '@angular/core';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
  //接收父组件传来的数据
  @Input() title:any;
  @Input() msg:any;
  //接收父组件传来的run方法
  @Input() run:any;

  //接收整个home父组件
  @Input() home:any;

  //获取父组件的数据
  getParentMsg(){
    alert(this.msg)
  }

  getParentRun(){
    //执行父组件的run方法
    this.run()

    console.log(this.home.msg);
    //通过接收整个Home组件,执行其中的run()方法
    this.home.run();
  }

  //
  constructor() { }
  ngOnInit() {
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值