I want to add multiline text message with proper line breaks that are provided by me.
this.sampleStringErrorMsg = 'The sample is not valid:\n' +
'- The key and key value are required in the sample.\n ' +
'- The delimiter must be entered when the sample contains several key-value pairs.\n' +
'- The delimiter must not be equal to the key or key value.\n';
sampleStringErrorMsg
is the text I show in snackbar.
Right now snackbar ommit \n
from the text and aligns the the whole message as shown in the image below
I just added white-space: pre-wrap
// ts
const msg: string = `Registration successful. \n Please, confirm your email`;
this._snackBar.open(msg, '', {
duration: 8000,
panelClass: ['success-snackbar']
});
//css
.success-snackbar {
background: #1fcd98;
white-space: pre-wrap
}
Your solution is to create a snackbar
component.
Without seeing your code, I'm guessing you have roughly something like this:
this.snackBar.open(this.sampleStringErrorMsg, null, {
verticalPosition: 'top'
});
As far as I'm aware, there's no way to achieve what you want by doing like the above.
ErrorSnackBarComponent
.
On the html
add the contents of your error message. It will look like something like this:<div>
<p>
<span>The sample is not valid:</span>
<br/>
<span>The key and key value are required in the sample.</span>
<br/>
<span>The delimiter must be entered when the sample contains several key-value pairs.</span>
<br/>
<span>The delimiter must not be equal to the key or key value.</span>
</p>
</div>
Make sure the ErrorSnackBarComponent
is referenced in the app.module.ts
under:
Use your recently created snackbar
component:
this.snackBar.openFromComponent(ErrorSnackBarComponent, { verticalPosition: 'top' });
Extra step
If you want to pass data to the ErrorSnackBarComponent
, change your snackbar component's constructor to this:
constructor(@Inject(MAT_SNACK_BAR_DATA) public data: any) { }
and instead of 3., use this:
this.snackBar.openFromComponent(ErrorSnackBarComponent, {
verticalPosition: 'top',
data: <YOUR_DATA_HERE>
});
and you should be able to use data
from the ErrorSnackBarComponent
and display your error message alongside with any other details such as properties.
Here is the documentation for snackbar
for your reference.
My reputation is too low to comment directly. I suggest an addition to Marias answer.
I am using Angular v7.3.7 and had to add ::ng-deep
, when I placed the CSS in a components CSS file like this
::ng-deep .success-snackbar {
background: #1fcd98;
white-space: pre-wrap
}
in order for it to work. Alternatively you could add the CSS to the global styles.css
file of your project.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With