[Angular2] Output 用法

從inside component 發送一個值到App component


1.import EventEmitter, Output
   emitSpot 就像是發射台,將東西發射出去

/* inside.component.ts */
------------------------------------
import { Component, OnInit, EventEmitter, Output } from '@angular/core';

@Component({
  selector: 'app-inside',
  templateUrl: './inside.component.html',
  styleUrls: ['./inside.component.css']
})

export class InsideComponent implements OnInit {

  @Output()
  emitSpot = new EventEmitter;

  sendTextToAppComp(val: string){
      console.log("outputText2App func working");
      console.log(val);
      this.emitSpot.emit(val)
  }

  constructor() { }

  ngOnInit() {
  }

}









2. html 就簡單按 click button 後呼叫sendTextToAppComp()將 input value 送到App Comp
/* inside.component.html */
----------------------------------------




3.

/* app.component.html */
----------------------------------------


  {{title}}

{{AppText}}



emitSpot)="OutputTextFromInsideComp($event)">



4.
/* app.component.ts */
----------------------------------------
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'app works!';
  public AppText = '';

  OutputTextFromInsideComp($event){
      console.log("OutputTextFromInsideComp Working");
      console.log("event: :"+$event);
      this.AppText = $event;
  }

}


流程大概就是
sendTextToAppComp() -> emitSpot.emit(val) -> (emitSpot) -> OutputTextFromInsideComp($event) -> this.AppText = $event;









沒有留言:

張貼留言

蔡松霖
Related Posts with Thumbnails