Angular – data share with different component

Parent share to child

//parent.component.ts
parentMsg:string = "This is a parent message."; //在Parent定義
//parent.component.html
<app-child [childMsg]="parentMsg"></app-child>   //綁定Parent Msg
//child.component.ts
import { import Input } from '@angular/core';  //需要先import
@Input() childMsg: string;  //定義Child 的Msg

Child share to parent

//child.component.ts
import { Output, EventEmitter } from '@angular/core'; //需要先import
@Output defineYourEvent = new EventEmiter<string>();   //根據data type 更改string做其他, 這個名稱由自己定義
sendFromChildMsg:string = "This message send form child.";
this.defineYourEvent.emit(sendFromChildMsg); //透過event 將 msg傳送到parent
//parent.component.ts
parentMsg:string = "default message."; //初始化 msg
updateParentMsg(receiveMsg:string):void{   //接收從child傳來的msg 
   this.parentMsg = receiveMsg;  //然後更新parent 的parentMsg
}
//parent.component.html
<app-child (defineYourEvent)="updateParentMsg($event)"></app-child>  //將child 的Event與parent 的function綁定

開始在上面輸入您的搜索詞,然後按回車進行搜索。按ESC取消。

返回頂部