Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 8: how can we detect re-rendering of a component (as event)

I need something as event to catch a re-rendering of a component in Angular 8

like image 659
Kamran Hasanoff Avatar asked Oct 20 '25 03:10

Kamran Hasanoff


1 Answers

I think if you are changing anything on UI/state then ngOnChanges is going to call.

ngOnChanges() (OnChanges) is called when a value bound to input has changed so you can run custom code when an input has changed.

ngDoCheck() (DoCheck) is called when change detection runs so you can implement your custom change detection action.

 ngOnChanges(changes: SimpleChanges) {
    // changes.prop contains the old and the new value...
     console.log('on change', changes)
  }

If you are handling HTTP response and you want to observe it then use BehaviorSubject.

Please check the following example,

Service to call API - TestService

        private test = new BehaviorSubject<any>(null);

        getTest() {
            // ...
            return this.http.get(_url, options)
                .map(response => {
                    const responseAsObject = response.json();
                    this.test.next(responseAsObject); // change the value!
                });
        }

In your component

        export class TestComponent implements OnInit{
            private testObj : any;

            constructor(
              private testService: TestService,
            ) {}

            ngOnInit() {
                this.testService.getTest
                    .subscribe(test => {
                        // here is the test object from the service, you can do whatever you want with it
                        // it fires when you get the updated response
                });  
            }
        }

Hope this will help you.

like image 165
Santosh Shinde Avatar answered Oct 21 '25 22:10

Santosh Shinde



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!