組件間傳值之@Output

對應(yīng)@input輸入傳值,也有@Output輸出傳值。
輸入傳值請我之前寫的一篇文章:http://www.itdecent.cn/p/686294cb2b29

例如:
A是B的父組件,B中有Input參數(shù)how,A中調(diào)用B組件,并傳入[Import]參數(shù)。B根據(jù)傳入的Import參數(shù),發(fā)射返回相應(yīng)的數(shù)據(jù)。

//A頁面代碼
    <table class="table table-bordered">
      <tbody>
      <tr>
       ......
      </tr>
      <tr *ngFor="let item of tasks|filter:'title':keyword;let i=index">
        ......
        <td>
          <app-jinji [Import]="item.jinji" (Export)="print($event)"></app-jinji>
        </td>
       ......
      </tr>
      </tbody>
    </table>
//A中ts代碼,定義print方法
......
  print(data) {
    console.log(data);
  }
......
//B中ts代碼
import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';

@Component({
  selector: 'app-jinji',
  templateUrl: './jinji.component.html',
  styleUrls: ['./jinji.component.css']
})
export class JinjiComponent implements OnInit {
  private shenheren: string;

  @Input('Import')
  private how: Number;

  @Output('Export')
  EmitData: EventEmitter<string> = new EventEmitter();

  constructor() {

  }

  ngOnInit() {
    // console.log('how:' + this.how);
    switch (this.how) {
      case 1:
        this.shenheren = '馬云';
        // console.log(1);
        break;
      case 2:
        this.shenheren = '李彥宏';
        // console.log(2);
        break;
      case 3:
        this.shenheren = '馬化騰';
        // console.log(3);
        break;
      case 4:
        this.shenheren = '柳傳志';
        // console.log(4);
        break;
      default:
        this.shenheren = '賈躍亭';
        // console.log(5);
        break;
    }
    this.EmitData.emit(this.shenheren);
  }
}

運行后,頁面console窗口中會打印出各位大佬的姓名,如圖:


image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容