Reputation: 115
I have a child component as
export class AlertComponent implements OnInit {
@Input() messageData: string | string[];
constructor() { }
ngOnInit(): void {
}
}
I have a parent component where in template I use the above component
<app-alert *ngIf="!!alertsCount" [type]="'danger'"
[messageData]="alertMessageData"></app-alert>
<mat-select class="select--width--130" (selectionChange)="changeAlertType($event)" [(value)]="alertType" placeholder="Alert Types">
<mat-option *ngFor="let alertType of alertTypes" [value]="alertType.name">
{{ alertType.name }}
</mat-option>
</mat-select>
in parent component ts
getAlertMessageData(alertType: string) {
switch (alertType) {
case 'firing':
case 'silenced':
case 'resolved':
this.alertMessageData = `There are ${this.alertsCount} ${alertType} alerts`;
break;
case 'all':
this.alertMessageData = `There are ${this.alertsCount} alerts`;
break;
}
console.log(this.alertMessageData);
}
changeAlertType(event: MatSelectChange) {
this.alertType = event.value;
this.getAlertMessageData(event.value);}
However the message data does not get updated when I change the selection of alert type, how do I pass messageData so that it is updated after I change mat-select?
Upvotes: 2
Views: 1358
Reputation: 4127
Try using Observable
messageSubject = new BehaviorSubject('');
alertMessage$ = this.messageSubject.asObservable();
// In your switch statement
this.messageSubject.next(`There are ${this.alertsCount} ${alertType} alerts`);
// Pass the observable in child component as input
<app-alert [messageData]="alertMessage$ | async"></app-alert>
Hope this will solve your issue.
Upvotes: 1
Reputation: 8773
What I see from the code is you are passing string or an array of string. When you are passing string, you can detect changes using ngOnChanges
provided that you are able to send data correctly from the parent component.
When you pass array, you need to changes the reference as array is an object and will be passed by reference and angular changes detection will not detect any changes to it even if you are using ngOnChanges
.
When you use ngOnchanges
you can use set property on @Input
and set the property and run the changeDetection.
export class ChildComponent implements OnChanges {
@Input() set messageData: any = [];
ngOnChanges(changes) {
// code here
// make changes here
}
}
I suggest you to read this. How change detection works?
Upvotes: 2