angular父子组件传值

父传子:@Input
子传父:@OutputEventEmitter
父调用子方法:@viewChild

一、父传子

ionic版本不同,父传子的方法有稍微不同,传值和接收的方法有所改变

1、首先在子组件中引入依赖

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

2、父组件:(ionic2)


父组件:(ionic3+)


3、子组件:(ionic2)

@Input('activeIndex') activeIndex: any

子组件:(ionic3+)

@Input() activeIndex: any

二、子传父

1、子组件
子组件引入依赖

import {Output, EventEmitter} from '@angular/core';

使用output定义传输的方法

@Output() event:EventEmitter = new EventEmitter()

通过事件触发父组件方法去传值

this.event.emit(this.text)

2、父组件

//father.html


//father.ts
father(event){
  consle.log(event)  //这里event就是子组件传过来的值
}

这里$不能省略,子组件的event名字对应父组件的(event)

三、父组件调用子组件方法

//父组件 father.html


father.js
import { ViewChild } from "@angular/core";
import { TabBarComponent } from '../../../components/tab-bar/tab-bar'
@ViewChild("tabbar")
tabbar:TabBarComponent

something(){
  this.tabbar.greet('Free')
}
//子组件
greet(name){
    alert(name+',你好')
  }

你可能感兴趣的:(angular父子组件传值)