angular组件传值

一:父传子

        子组件可以获取父组件的数据

        子组件可以执行父组件的方法

        子组件通过@Input装饰器进行接收父组件传过来的值

父组件
export class AppComponent {
  public title = '父组件';

  run(){
    alert('父组件方法')
  }
}

//在父组件中引入子组件并且以变量的形式给子组件传值
<app-children [title]="title" [run]="run"></app-children>

子组件引入Input
import { Component, OnInit, Input } from '@angular/core';


export class ChildrenComponent implements OnInit {
//通过@Input 接收父组件传过来的值
  @Input() title : any;
  @Input() run : any;
  constructor() { }

  ngOnInit(): void {
  }

   // 获取父组件的方法
  getRun(){
    this.run()
  }

}
//子组件直接通过模板变量使用即可
<p>{{title}}</p>
<p (click)="getRun()">接收父组件的自定义方法</p>

也可以把整个父组件传递给子组件:

eg:在子组件上挂载父组件 [home] = 'this' this指的就是整个父组件, 在子组件上接收 首先定义一个初始值,然后在掉用父组件的方法/值  this.home.run()/this.home.title

二:子传父

        父组件可以获取子组件的数据

        父组件可以获取子组件的方法

        ①:子组件可以通过@Output装饰器和EventEmitter触发父组件的方法

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

/**  子传父 通过@Output() 装饰器传递 
        private 定义私有化变量
        new EvenrEmitter 实例
  */
@Output() private outer = new EventEmitter<string>();

// 传递数据
  outMsg(){
    // alert('chuandishuju')
    this.outer.emit(this.msg)
}

<button (click)="outMsg()">子组件通过@Output给父组件传递数据</button>

父组件
<app-children (outer)="recive($event)"> </app-children>

//获取子组件传递过来的数据
recive(e:any){
    alert(e)
}

        ②:父组件通过@ViewChild 主动获取子组件的数据和方法,通过事件进行获取

        

子组件
public msg ='我是子组件的msg'

父组件
<app-children #footer></app-children>

//通过事件主动获取子组件的数据
<button (click)="getMsg()">获取子组件的msg</button>
//引入ViewChild
import { Component,ViewChild } from '@angular/core';

@ViewChild('footer') footer:any;

getMsg(){
    alert(this.footer.msg)
 }

        

三:非父子组件

        组件之间互相传值

        共享方法

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值