Angular Диалог материалов закрывается немедленно - PullRequest
0 голосов
/ 18 февраля 2020

Я пытаюсь открыть диалоговое окно Angular Material из моего компонента. Но диалоговое окно закрывается сразу после его открытия.

Я знаю, что есть некоторые похожие вопросы о Stackoverflow, но их ответы, похоже, не работают для меня. Не уверен, что проблема заключается в вызове функции диалога из полной части подписки.

ExampleDialogComponent.ts

export class ExampleDialogComponent implements OnInit {

  inputVal1: string;
  inputVal2: string;

  constructor(public dialogRef: MatDialogRef<ExampleDialogComponent>,
              @Inject(MAT_DIALOG_DATA) public data: any, private formBuilder: FormBuilder) {
    this.inputVal1 = data.inputVal1;
    this.inputVal2 = data.inputVal2;
  }

  ngOnInit() {
    this.firstFormGroup = this.formBuilder.group({
      firstCtrl: ['', Validators.required]
    });
    this.secondFormGroup = this.formBuilder.group({
      secondCtrl: ['', Validators.required]
    });
  }

  onCloseConfirm() {
    setTimeout(() => {
      this.dialogRef.close({
      message: 'Confirm',
      outputVal1: this.inputVal1,
      outputVal2: this.inputVal2,
      });
    }, 0);
  }
}

ExampleDialogComponent. html

<mat-step>
      <ng-template matStepLabel>last step</ng-template>
      <mat-dialog-actions>
        <button mat-button [mat-dialog-close]="onCloseConfirm()">add</button>
        <button mat-button mat-dialog-close>close</button>
      </mat-dialog-actions>
</mat-step>

MainCompontent.ts

openModal() {
    this.inputs = [];
    this.http.getInputs().subscribe(
      data => {
        data.forEach(element => this.inputs.push(element));
      },
      (err) => {
        console.log(err);
      },
      () => {
        this.openAddDialog();
      });
  }

  openAddDialog() {
    const dialogConfig = new MatDialogConfig();

    dialogConfig.disableClose = true;
    dialogConfig.autoFocus = true;
    dialogConfig.data = {
      inputValue1: 'test 1',
      inputValue2: 'test 2',
    };

    const dialogRef = this.dialog.open(ExampleDialogComponent, dialogConfig);

    dialogRef.afterClosed().subscribe(result => {
      console.log('Dialog was closed');
      console.log('result: ' + result);

      this.http.createResultinDB(result);
        .subscribe(subData => console.log(subData), error => console.log(error));
    });
  }

  getDeliveryPackageList(): Observable<any> {
    return this.http.get(`${this.baseUrl}`);
  }

Большое спасибо за вашу помощь .

Ответы [ 4 ]

3 голосов
/ 18 февраля 2020

Эта строка вызывает проблему:

<button mat-button [mat-dialog-close]="onCloseConfirm()">add</button>

Функция onCloseConfirm вызывается сразу после открытия диалогового окна из-за того, как работает привязка angular.

У вас есть пара вариантов. Вы можете использовать обработчик щелчка на кнопке для вызова вашей функции:

<button mat-button (click)="onCloseConfirm()">add</button>

Вы или можете продолжать использовать [mat-dialog-close], и ​​не использовать свою функцию onCloseConfirm:

<button mat-button [mat-dialog-close]="[inputVal1, inputVal2]">add</button>
0 голосов
/ 01 мая 2020

удаление ссылки решило мою проблему в моем случае, я удаляю ссылку из

 <a class="fa fa-user" aria-hidden="true" href="/#/home/homepage" (click)="opendialogue()" >&nbsp;Profile</a>

Я удаляю нежелательную ссылку, т.е. href="/#/home/homepage", чтобы преодолеть из автоматов c закрытие диалога

0 голосов
/ 26 марта 2020

Для меня источник проблемы был другим. У меня была гиперссылка со свойством (click). Когда я щелкнул гиперссылку, была вызвана функция, открывающая диалоговое окно, но событие было передано в href элемента <a>, закрывая диалоговое окно сразу после его открытия. Решением было остановить распространение.

<a href="#" (click)="$event.preventDefault(); aboutMyApp();">About...</a>

...

aboutMyApp() {
    const dialogRef = this.dialog.open(AboutDialog, { width: '400px', height: 'auto' });
}

Надеюсь, это может быть полезным для всех.

0 голосов
/ 18 февраля 2020

Проблема в том, что вам нужно добавить в ваш app.module.ts массив entryComponents с именем компонента Dialog следующим образом:

@NgModule({
  entryComponents: [
    ExampleDialogComponent
  ],
  declarations: [...],
.
.
.
})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...