查看: 26|回覆: 0

angular父子组件相互传值

[複製鏈接]

1

主題

0

回帖

0

積分

热心网友

金币
0
閲讀權限
220
精華
0
威望
0
贡献
0
在線時間
0 小時
註冊時間
2011-9-8
發表於 2019-11-29 17:33:00 | 顯示全部樓層 |閲讀模式
// 调用子组件  向子组件传值和方法的方式
<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)

 

 

 

 

 

 

 

 

 

 

 



来源:https://www.cnblogs.com/cazj/p/11959189.html
回覆

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 立即注册

本版積分規則

相关侵权、举报、投诉及建议等,请发 E-mail:qiongdian@foxmail.com

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部