angular父子组件相互传值

// 调用子组件  向子组件传值和方法的方式
<app-header [title]="title" [run]="run" [parent]="this"></app-header>

在子组件中,引入Input,通过@input() 方式引入,即可通过this.xxx使用

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

@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.less']
})
export class HeaderComponent implements OnInit {
constructor() { }
@Input() title: any;
@Input() run: any;
@Input() parent: any;
ngOnInit() {
}
getPatrent() {
this.run();
this.parent.run(); // 可以直接调用父组件的属性和方法
}
}

 子组件向父组件间传值

1、通过ViewChild获取子组件的方法和属性 

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

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.less']
})
export class HomeComponent implements OnInit {
  public title: any = '首页';
  @ViewChild('child', {static: false}) child: any;
  constructor() { }
  ngOnInit() {
  }
  run() {
    alert('父组件');
  }
  getChildValue() {
    this.child.childRun(); // 通过这种方式可以获取到子组件的方法和属性值
  }
  childFun(e) {
    console.log(e);
  }
}

2、通过事件广播

子组件中引入Output和EventEmitter,再使用@Output定义,通过emit分发

 

 

 父组件中接收(同vue中的emit)

 

 

 

 

 

 

 

 

 

 

 

posted @ 2019-11-29 17:33  陈小作  阅读(2626)  评论(0编辑  收藏  举报