Search code examples
angulartypescriptdomangular2-templateangular2-changedetection

How to refresh a part of the page view without refreshing the entire page in angular on a click event?


I am building a chat application using Angular. I have two components for the chat. One for each user. I am using a radio button component which creates a new message as radio button. The user selects an option. Once the user clicks on submit button the radio button message is edited and a new message is printed with the option selected by the user.

You can see the demonstration in the plunker below. If user1 creates the radio message and submits the option in the same view, it works as expected. But if user1 creates the radio message and user2 submits the option, then the radio button message is not edited but only generates a new message with the option selected.

The problem I am facing here is that I am unable to refresh the view on the click event. This will display the edited radio button message by removing the options to select.

There is an API available in Angular: ChangeDetection. It goes something like this: ANGULAR CHANGE DETECTION

edit(message: Message): void {
        let result = JSON.stringify(message);
        if (!result) {
            return;
        }
        this.appService.update(this.message)
            .then(() => {
                return null;
            });
    }

But I am unable to use this API on click event.

Plunker for the same is attached: Angular chat application

Is there any other way or work around to get this working? Feel free to fork the plunker code and edit if needed.


Solution

  • Remove setMessage and getMessage methods from AppService.

    By using these methods you hold object in shared service. And as object and array are mutable you will get a lot of problem with such implementation.

    I would use @Input property for Radio component

    app.component.html home.component.html

    <mm-radio-message [message]="message" ...></mm-radio-message>
    

    radio.component.ts

    @Input() message: Message;
    

    Forked Plunker