angular 组件之间的通信

父子组件:

1.父组件调用子组件时,绑定自定义属性赋值为父组件中的自定义变量。父组件通过该变量传递信息给子组件。

父组件homes

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

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

  constructor() { }
  //父组件通过调用子组件定义的title属性绑定一个值
  title='我是父组件home给我的title信息';

  ngOnInit(): void {
    
  }

}

 

HTML:

<div id='home'>
<!--调用子组件,定一个一个自定义属性,如下为forChile,父组件的ts文件中通过title传递这个值-->
标题:<app-header [forChile]='title'></app-header>
<line></line>
<hr>
<br>
我是home组件。
</div>

父组件news 

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

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

  constructor() { }

  ngOnInit(): void {
  }

//父组件定义的方法
  run(){
    alert('我是父组件的方法,被子组件执行了');
  }
}

 

<div id='new'>
    <!--调用子组件,定一个一个自定义属性,如下为forChile,父组件的ts文件中通过title传递这个值-->
    我是子组件header:<app-header [forChile]='title' [method]='run'></app-header>
    <hr>
    <br>
    我是news组件。
    
    </div>
    
    

2.子组件:

  • //导入Input

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

  •  //引入父组件传递过来的信息,用变量receivedMsg接收

      @Input('forChile') receivedMsg:any;

      //引入方法

      @Input('method') gotMethod:any;

TS代码:

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

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

  constructor() { }
  //引入父组件传递过来的信息,用变量receivedMsg接收
  @Input('forChile') receivedMsg:any;
  //引入方法
  @Input('method') gotMethod:any;
  ngOnInit(): void {
  }

  execute(){
    //执行方法
    this.gotMethod() ;
  }

}

HTML:

<!--可以直接展示ts定义的变量-->
<div>{{receivedMsg}}<div>
<button (click)='execute()'>调用父组件的方法</button>

3.子组件可以使用或者调用方法

<!--可以直接展示ts定义的变量-->

<div>{{receivedMsg}}<div>

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

 

 

效果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值