Mat-dialog无法在页面上正确打开

时间:2020-07-18 21:13:18

标签: angular angular-material mat-dialog

每当加载特定的URL时,我都试图打开mat-dialog。当前,仅在重新加载整个页面时才起作用。我希望它在加载此特定角度路由时启动mat-dialog,无论是整页加载还是使用角度路由器的已加载角度应用程序。 我尝试将以下代码放入ngOnInit()内,也尝试在ngAfterViewInit()内进行同样的问题。我尝试的另一件事是在获取userIsAuthenticated值之后将其放在构造函数中,但是存在同样的问题。 感谢您的帮助!

 ngAfterViewInit() {
    if (!this.userIsAuthenticated) {
      const dialogRef = this.dialog.open(ConfirmationAgeComponent, {
        panelClass: "dialogBoxStyler"
      });

      dialogRef
        .afterClosed()
        .pipe(takeUntil(this.destroy))
        .subscribe(result => {
          if (result) {
            this.over21Agreed = true;
          }
        });
    }
  }

我还尝试将以下内容添加到构造函数中:

 constructor(private router: Router){
    this.url = this.router.url;
    if (this.url === '/' || this.url.includes('search-results')) {
      alert("HERE")
    }
}

,但警报仅在第一次弹出。如果我单击地址栏中的URL以突出显示该URL并按Enter,则不会出现警报。

3 个答案:

答案 0 :(得分:1)

我们以错误的方式使用了角生命周期

定义对话框:-

 openAgeConfirmationDialog() {

    const dialogRef = this.dialog.open(ConfirmationAgeComponent, {
      panelClass: 'dialogBoxStyler'
    });

    dialogRef
      .afterClosed()
      .pipe(takeUntil(this.destroy))
      .subscribe(result => {
        if (result) {
          // I defined over21Agreed to true so that component appears on screen fyi
          this.over21Agreed = true;
        }
      });

  }

然后,在ngOninit()中的openAgeConfirmationDialog()ngOnInit()中分别调用router.events

ngOnInit() {

    this.openAgeConfirmationDialog();

    this.router.events.pipe(
      filter((event: RouterEvent) => event instanceof NavigationEnd),
      takeUntil(this.destroy),
      debounceTime(1000)
    ).subscribe(() => {
      this.openAgeConfirmationDialog();
    });

我们之所以使用debounceTime,是因为它绕过了由路由更改引起的问题。

答案 1 :(得分:0)

您应该在主app.component构造函数中订阅路由器事件,以便能够跟踪导航,例如:

constructor(private router: Router) {
        router.events.subscribe((event: RouterEvent) => this.handleEvent(event));
}

handleEvent(event: RouterEvent) {
        if (event instanceof NavigationStart) {
            // do your thing here using `event.url` for example
        }
        if (event instanceof NavigationEnd || event instanceof NavigationCancel || event instanceof NavigationError) {
            // or here
        }
}

有关RouterEvent的文档可以找到here

答案 2 :(得分:0)

一种实现方法是将对话框组件作为标题组件的子代放置在路由配置中,并提供您希望对话框组件作为routerLink在标题组件中打开的“ URL”。看一下下面的stackblitz链接。希望这就是您想要的。.

Loading mat-dialog component on a particular route