I have a registration form and i want to show a message to the user of whether he was successful or not, for this i am using a snackbar that i made as an angular component and that i open with a button in my app component, however, i want to pass the value of a boolean to the snackbar component so that based on the value it shows a different message. My code is something like this:
app-component.html
<button mat-raised-button type="submit" id="registerButton" (click)="openSnackBar()">
<p id="registerText">Register</p>
</button>
I'm using this function to open the snackbar in my app-component file:
app.component.ts
openSnackBar(){
this.snackbar.openFromComponent(SnackbarComponent, {
duration: 2000,
});
}
This is my snackbar component template: snackbar.component.html
<span class="text" matSnackBarLabel *ngIf="isRegistrationSuccessful == true; else registrationFailed">
You have registered successfully
</span>
<span matSnackBarActions>
<button mat-button matSnackBarAction (click)="snackBarRef.dismissWithAction()">🍕</button>
</span>
<ng-template #registrationFailed>
<span class="text" matSnackBarLabel>
Failed to register
</span>
<span matSnackBarActions>
<button mat-button matSnackBarAction (click)="snackBarRef.dismissWithAction()">🍕</button>
</span>
</ng-template>
and this is what i have on my file: snackbar.component.ts
export class SnackbarComponent implements OnInit {
constructor() { }
ngOnInit() {
}
isRegistrationSuccessful: boolean = false;
snackBarRef = inject(MatSnackBarRef);
}
what i want to do is set the value of isRegistrationSuccessful
from my app.component.ts when i trigger the snackbar and show a different message depending of said value, which is why i'm using ng-template, however, i have no idea how to do this.
Looking at the Angular Material Doc, it looks like you can pass data to your custom snackbar via the constructor with something like this:
export class SnackbarComponent {
constructor(@Inject(MAT_SNACK_BAR_DATA) public isRegistrationSuccessful: boolean) { }
}
I think this makes the code to call showing this component to be something like this:
openSnackBar() {
// assuming you have some way to get whether registration was successful
let result = this.someRegistrationService.getRegistrationResult();
this.snackbar.openFromComponent(SnackbarComponent, {
isRegistrationSuccessful: result,
});
}