Reputation: 21
I'm trying to create an Angular component that is a Mat Dialog when the screen is bigger than 500px and Mat Bottom Sheet when the screen is lower.
The following code is just a basic example of the code I have. However, the actual code is much more complex, with hundreds of lines of HTML, SCSS, and JS. I don't want to create two separate components (one as a Mat Dialog and the other as a Mat Bottom Sheet) because they would have almost identical code. Therefore, I am looking for a way to combine both components into a single one.
Dialog/Bottom Sheet Component
export interface MyComponentData {
firstName: string,
lastName: string
}
@Component({
selector: "my-component",
templateUrl: "./my-component.component.html",
styleUrls: ["./my-component.component.scss"]
})
export class MyComponent {
constructor(
@Inject(MAT_BOTTOM_SHEET_DATA) public bottomSheetData: MyComponentData,
@Inject(MAT_DIALOG_DATA) public dialogData: MyComponentData,
public bottomSheetRef: MatBottomSheetRef<MyComponent>,
public dialogRef: MatDialogRef<MyComponent>
) {}
}
Main Component
@Component({
selector: "main-component",
templateUrl: "./main-component.component.html",
styleUrls: ["./main-component.component.scss"]
})
export class MainComponent {
constructor(private bottomSheet: MatBottomSheet, private dialog: MatDialog) {}
onClick(temp: MyComponentData): void {
if(window.innerWidth > 500) {
this.dialog.open(MyComponent, {data: temp})
} else {
this.bottomSheet.open(MyComponent, {data: temp})
}
}
}
When the screen width is less than 500 pixels, and I try to open it as a bottom sheet, it shows the error message NullInjectorError: No provider for InjectionToken MatDialogData!
. On the other hand, when I try to open it as a dialog, it shows the error message Error: NullInjectorError: No provider for InjectionToken MatBottomSheetData!
.
When I remove public bottomSheetRef: MatBottomSheetRef<MyComponent>
and @Inject(MAT_BOTTOM_SHEET_DATA) public bottomSheetData: MyComponentData
from the constructor, the dialog starts to work. Similarly, if I remove public dialogRef: MatDialogRef<MyComponent>
and public dialogRef: MatDialogRef<MyComponent>
from the constructor, the bottom sheet works properly.
Can anyone help me with resolving this issue and getting it to work as expected?
Upvotes: 2
Views: 310