I am working on an app in Angular 14.
The app is designed to contain multiple forms in various components which is why I thought it was a good idea to create a reusable component for error messages.
In form.component.ts
I have:
import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { FormService } from '../services/form.service';
@Component({
selector: 'app-form',
templateUrl: './form.component.html',
styleUrls: ['./form.component.css'],
})
export class FormComponent {
public errorMessage: any = null;
// More code
public sendFormData() {
this.formService.sendFormData(this.formService.value).subscribe(
(response) => {},
(error) => {
this.errorMessage = error.message;
}
);
}
}
In errors.component.ts
I have:
import { Component } from '@angular/core';
@Component({
selector: 'app-errors',
template: `<div class="alert-error">{{ errorMessage }}</div>`,
styles: [
`
.alert-error {
color: #721c24;
background-color: #f8d7da;
border-color: #f5c6cb;
padding: 0.75rem 1.25rem;
margin-bottom: 1rem;
text-align: center;
border: 1px solid transparent;
border-radius: 0.25rem;
}
`,
],
})
export class ErrorsComponent {}
I call the abve component in app.component.html
on the condition that there are errors:
<app-errors *ngIf="errorMessage"></app-errors>
<app-form></app-form>
There is a Stackblitz HERE.
The problem
In reality, even though there are errors (the errorMessage
is different from null
), the ErrorsComponent component is no rendered.
Questions
- What is my mistake?
- What is the most realizable way to fix this problem?