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)

 

 

 

 

 

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM