1. 程式人生 > 實用技巧 >Angular:元件之間的通訊@Input、@Output和ViewChild

Angular:元件之間的通訊@Input、@Output和ViewChild

①父元件給子元件傳值

1、父元件:

ts:
export class HomeComponent implements OnInit {
  public hxTitle = '我是首頁的頭部';

  constructor() { }
  ngOnInit(): void {
  }

  run(): void {
    alert('我是父元件的方法');
  }

}

html:
<app-header [hxTitle222]="hxTitle" [run]="run" [home]='this'></app-header>

2、子元件:

ts:
import { Component, OnInit, Input } from 
'@angular/core'; @Component({ selector: 'app-header', templateUrl: './header.component.html', styleUrls: ['./header.component.less'] }) export class HeaderComponent implements OnInit { @Input() hxTitle222: any; @Input() run: any; @Input() home: any; constructor() { } ngOnInit(): void
{ } getPRun(): void { this.run(); this.home.run(); console.log(this.home); } } html: <p>{{hxTitle222}}</p> <button (click)="getPRun()">我要執行父元件的方法</button>

②子元件給父元件傳值

1、子元件:

ts:
import { Component, OnInit, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 
'app-newschild', templateUrl: './newschild.component.html', styleUrls: ['./newschild.component.less'] }) export class NewschildComponent implements OnInit { public hxMsg = '我是新聞孩子的資訊'; @Output() hxMsg2 = new EventEmitter(); constructor() { } ngOnInit(): void { } run(): void { alert('我是新聞孩子的run方法'); } hxRun(): void { this.hxMsg2.emit(this.run); //廣播方法 } } html: <button (click)="hxRun()">我要觸發事件,並將值傳給父元件</button>

2、父元件:

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

@Component({
  selector: 'app-news',
  templateUrl: './news.component.html',
  styleUrls: ['./news.component.less']
})
export class NewsComponent implements OnInit {

  constructor() { }

  ngOnInit(): void {
  }

  getRun2(e): void {
    console.log(e);
  }
}

html:
<app-newschild (hxMsg2)="getRun2($event)"></app-newschild>