---
# System prepended metadata

title: Angular子母component之間傳值
tags: [Angular]

---

###### tags: `Angular`

# Angular子母component之間傳值

## 對話框component結束後傳值回母component

### 『dialogRef.close(資料)』的傳值方式

子 component 設定 submit 事件：
```javascript=
onSubmit() {
this.dialogRef.close('submit');
}
```
母 component 用 dialogRef.afterClosed().subscribe(**result**=>{}取值
**result** 就是剛剛 close 丟出去的資料，名稱可以隨意取
```javascript=
openDialog() {
const dialogRef = this.dialog.open(DialogComponent, {
  // dialog open parameters
        });
 dialogRef.afterClosed().subscribe(result => {
          if (result === 'submit') {
            }}}
```


## EventEmitter連動方式

對話框 component 中 new 一個 EventEmitter 綁到按鈕動作上
```javascript=
onAdd = new EventEmitter();
onButtonClick() {
  this.onAdd.emit();
}
```

母 component 收到對話框中按鈕被按下時傳入的值(如有)
```javascript=
let dialogRef = this.dialog.open(Component);
const sub = dialogRef.componentInstance.onAdd.subscribe(() => {
  // do something
});
dialogRef.afterClosed().subscribe(() => {
  // unsubscribe onAdd
});
```

## bind方法
頁面放置一個打開對話框的按鈕，留{{name}}接收即時回傳的值
```javascript=
<mat-card>
  <mat-card-title>Opend dialog to change name</mat-card-title>
  <mat-divider></mat-divider>
  <mat-card-content>
    <br>
    Hello , <font color="tomato">{{ name }}</font><br><br>
    Click <a href="javascript:void(0)" (click)="openDialog()">here</a> to open input
    dialog.
  </mat-card-content>
</mat-card>
```
頁面 Component 開啟對話框時傳入一個值，該值綁定頁面 Component
```javascript=
export class AppComponent {
  constructor(public dialog: MatDialog) {}
  name = 'World';
  openDialog() {
    this.dialog.open(DialogComponent, {
      width: '300px',
      data: { callback: this.callBack.bind(this), defaultValue: this.name }
    });
  }
  callBack(name: string) {
    this.name = name;
  }
}
```
對話框 html 上的按鈕方法可將填入的值傳回頁面 Component 的 method
```javascript=
<mat-dialog-actions align="end">
  <button mat-button mat-dialog-close>Close</button>
  <button mat-button color="primary" (click)="data.callback(input.value)">
    Submit
  </button>
</mat-dialog-actions>
```
設定即時回傳name變數的component
```javascript=
import { Component, Input } from '@angular/core';
@Component({
  selector: 'hello',template: `<h1>Hello {{name}}!</h1>`,styles: [`h1 { font-family: Lato; }`]
})
export class HelloComponent  {
  @Input() name: string;
}
```

