我的ts代码是:
if(cnfrm){
let dialogRef = this.dialog.open(this.callAPIDialog)
dialogRef.afterClosed().subscribe(result => {
console.log(`Dialog result: ${result}`); // which will be value
})
}
我的html代码是:
<ng-template #callAPIDialog>
<textarea #name matInput placeholder="Leave a comment" formControlName="description" required></textarea>
<button type="button" (click)="dialogRef.close(name.value)">Submit</button>
</ng-template>
因此,此弹出窗口打开,我可以在textArea中写入任何数据,但是不幸的是,单击“提交”按钮后,弹出窗口没有关闭,并且我在ts文件中没有价值。如果我在弹出框外单击,则在TS中得到未定义的值。
我需要解决方案。1.为什么TextArea数据没有传输到TS文件中?2.在TextArea中写入任何数据并单击“单击”按钮后,弹出窗口必须关闭,防止用户单击“屏幕”的其他部分。
这是最简单的实施方法。
https://stackblitz.com/edit/angular-ott6js-hpfsuv?embed=1&file=src/app/dialog-overview-example.ts
这里的关键是捕获更改时的数据:
html:
<h1 mat-dialog-title>Hi {{data.name}}</h1>
<div mat-dialog-content>
<p>What's your favorite animal?</p>
<mat-form-field>
<mat-label>Favorite Animal</mat-label>
<input matInput (change)="changeAnimal($event)">
</mat-form-field>
</div>
<div mat-dialog-actions>
<button mat-button (click)="onNoClick()">No Thanks</button>
<button mat-button [mat-dialog-close]="data.animal" cdkFocusInitial>Ok</button>
</div>
脚本
import {Component,Input, Inject, OnInit} from '@angular/core';
import {MatDialog, MatDialogRef, MAT_DIALOG_DATA} from '@angular/material/dialog';
import { FormBuilder, FormControl, FormGroup } from '@angular/forms';
export interface DialogData {
animal: string;
name: string;
}
/**
* @title Dialog Overview
*/
@Component({
selector: 'dialog-overview-example',
templateUrl: 'dialog-overview-example.html',
styleUrls: ['dialog-overview-example.css'],
})
export class DialogOverviewExample implements OnInit {
myForm: FormGroup;
animal: string;
name: string;
constructor(public dialog: MatDialog, private formBuilder: FormBuilder) {}
ngOnInit(){
this.myForm = this.formBuilder.group({
name: new FormControl(null),
animal: new FormControl(null)
})
}
openDialog(): void {
const dialogRef = this.dialog.open(DialogOverviewExampleDialog, {
width: '250px',
data: this.myForm.value
});
dialogRef.afterClosed().subscribe(result => {
console.log('The dialog was closed', result);
// this.myForm.setControl('animal', result);
this.myForm.controls.animal.setValue(result);
});
}
}
//The dialog component. We are using ngValue accessor to get the values.
@Component({
selector: 'dialog-overview-example-dialog',
templateUrl: 'dialog-overview-example-dialog.html',
})
export class DialogOverviewExampleDialog {
animal: string;
constructor(
public dialogRef: MatDialogRef<DialogOverviewExampleDialog>,
@Inject(MAT_DIALOG_DATA) public data: DialogData) {}
changeAnimal(ev: any) {
this.data.animal = ev.target.value;
}
}