首页 文章

根据组件中的按钮调用不同的对话框窗口

提问于
浏览
0

我有一个名为 home 的组件,其中包含一些描述和 button . 如下图所示 .

enter image description here

  • 我在另外两个名为 carbike 的组件中重用了相同的 home 组件 .

  • car 组件中单击按钮(i,主页组件中的e按钮),我在对话框窗口中调用一个名为 car-booking 的组件 . 此要求现已完成 .

  • 但我也在 bike 组件中重新使用 home 组件 . 在自行车组件中单击按钮(i,主页组件中的e按钮),我应该在对话框窗口中调用另一个组件 (ex bike-booking) .

如何根据其在组件中的存在更改特定按钮的 (click) 功能?

stackblitz DEMO

1 回答

  • 1

    您可以使用 @Output 向容器发出事件,然后在容器组件中,您可以选择在收到事件时要执行的操作 .

    HomeComponent

    export class HomeComponent  {
    
         @Output() openDialog = new EventEmitter();
    
         constructor(public dialog: MatDialog) {}
    
      open(): void {
         this.openDialog.emit();
      }
    
    }
    

    HomeComponent's template

    Hai!! welcome to our application..
    
    <div style="padding:30px;">
      <button mat-raised-button  (click)="open()" color="primary">ADD</button>
    </div>
    

    BikeComponent's template

    <app-home (openDialog)="openDialog($event)"></app-home>
    

    BikeComponent ts

    export class BikeComponent implements OnInit {
    
      constructor() { }
    
      ngOnInit() {
      }
    
      openDialog($event: any) {
         // open desired bike component
      }
    
    }
    

    CarComponent's template

    <app-home (openDialog)="openDialog($event)"></app-home>
    

    CarComponent ts

    export class CarComponent implements OnInit {
    
      constructor() { }
    
      ngOnInit() {
      }
    
      openDialog($event: any) {
         // open desired car component
      }
    
    }
    

    看看官方文件:https://angular.io/guide/component-interaction

相关问题