0

I have an issue with ngonchanges not firing.

I have this component:

@Component({
    selector: 'conversation-detail',
    templateUrl: './conversation-detail.component.html'
})
export class ConversationDetailComponent implements OnChanges{
    @Input()
    selectedConversation: Conversation;

    title = 'Conversation Detail';    
    convoMessages: Array<Message> = [];


    constructor(
            private _messageService: MessageService
    ){};

    ngOnChanges(changes: SimpleChanges){        
        this.getMessages();
    }

    ngOnInit(): void{

    } 

    private getMessages(){
        if(this.selectedConversation != undefined){
            this._messageService.getMessagesForConversation(this.selectedConversation.ConversationId).then(
                data => {
                    if (data) {
                        this.convoMessages = data.serviceResult as Array<Message>;
                    } else {
                        //This really should never happen
                        console.error('Error retrieving users data: Data object is empty');
                    }
                },
                error => {
                    //loader.dismiss();
                    console.error('Error retrieving users data');
                    console.dir(error);
                }
            );
        }
    }    

}

The ngonchanges will fire the first time selectedConversation changes. GetMessages is called and it loads in the message data. After that ngonchanges no longer fires when selectedConversation changes.

If I comment out the function call to getMessages then ngonchanges will fire every time selectedConversation changes.

so, I'm not sure what is going on in getMessages that cuts off ngonchanges from firing off. The request returns data and the call ends. Anyone have any ideas?

HarvP
  • 190
  • 3
  • 13

2 Answers2

1

Please change your component as :

@Component({
    selector: 'conversation-detail',
    templateUrl: './conversation-detail.component.html',
    changeDetection: ChangeDetectionStrategy.Default
})

This works fine for me.

0

ngOnChanges only fire if @Input change reference, for example Input type of string, boolean, number, immutable object.

assume [selectedConversation] bind to an array arrSelected, if you do something like arrSelected.push, the array does not change ref so ngOnChanges won't fire.

so you need using immutable array, using concat, slice, etc to change the array reference

Tiep Phan
  • 12,386
  • 3
  • 38
  • 41