简体   繁体   中英

Angular 6 - MatDialog - EventEmitter - share object to parent component from MatDialog

Right now able to communicate between two components. but don't know how to pass user (selected) entered value as Object via event emitter from MatDialog component to the parent component. Here I want to pass selected option value and text area value as object after clicking the submit button.

dialog.html

          <mat-select [(ngModel)]="selectedIssue"  [ngModelOptions]="{standalone: true}">
            <mat-option  [value]="option1">Option AA</mat-option>
            <mat-option  [value]="option2">Option BB</mat-option>
            <mat-option  [value]="option3">Option CC</mat-option>
            <mat-option  [value]="option4">Option DD</mat-option>
            <mat-option  [value]="option5">Option EE</mat-option>
          </mat-select>


         <div>
            <textarea class="mention-reason" [(ngModel)]="reason" [ngModelOptions]="{standalone: true}"></textarea>
        </div>

    <button class="cancel" matDialogClose>Cancel</button>      
    <button class="submit" [mat-dialog-close] (click)="submitUserReason()">Submit</button></span>

dialog.ts

onSubmitReason = new EventEmitter();
    submitUserReason(): void {
        this.onSubmitReason.emit('hello');
    }

    onConfirmClick(): void {
        this.dialogRef.close(true);     
    }

parent.ts

callSupport() {
        const dialogRef = this.dialog.open(customerSupportComponent);
        const subscribeDialog = dialogRef.componentInstance.onSubmitReason.subscribe((data) => {
          console.log('dialog data', data);
          //i can see 'hello' from MatDialog
        });

    dialogRef.afterClosed().subscribe(result => {      
      subscribeDialog.unsubscribe();
    });

Thanks so much whoever helping.

I assume there are two buttons. 1) submit 2) close

So, If you want selected data in parent component on submit button click then,

submitUserReason(): void {
   this.dialogRef.close({ option: userSelectedOption, reason:userReason });
}

And in parent component,

dialogRef.afterClosed().subscribe(result => {
console.log(result);
});

In your dialog.ts you want to pass your selected option instead of just a string. Something like:

submitUserReason(): void {
   this.onSubmitReason.emit(selectedIssue);
}

You can emit whatever you want (depending on how you've typed things) so if you'd like to pass more data you could also pass an object:

submitUserReason(): void {
   let data = { issue : selectedIssue, reason: userReason};
   this.onSubmitReason.emit(data);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM