I'm currently developing a Chrome extension that utilizes a background.js
file to fetch data under specific conditions.
- When these conditions are met, I activate the pageAction
- Upon clicking the extension icon, a message is sent to "
background.js
" and the response contains the requested data.
Despite updating the component property, the changes aren't immediately reflected in the UI.
background.js
chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
sendResponse(this.data);
});
app.component.ts
import {Component, OnInit} from '@angular/core';
// @ts-ignore
const CHROME = chrome;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'Title';
response: any;
constructor() {}
ngOnInit() {
CHROME.runtime.sendMessage({
message: 'Give me data'
}, response => {
this.title = response.title;
this.response = JSON.stringify(response);
console.log(response.title);
});
}
clickMe() {
console.log('Before:' + this.title);
this.title += ' !!';
}
}
app.component.html
<div style="text-align:center">
<h1> Title: {{title}}</h1>
<h1> Response: {{response}}</h1>
</div>
<button (click)="clickMe()" >Click Me!</button>
I have discovered that due to the nature of updating app.component's property from another scope, Angular struggles to recognize these changes and update the UI accordingly.
To address this issue, I included a button that triggers an update in Angular when clicked, allowing for proper UI updates.
Is there a way to ensure the UI updates automatically without manual intervention?
Update
Because Angular couldn't detect the changes made in another scope, I had to explicitly trigger an update:
constructor(private changeDetectorRef: ChangeDetectorRef) {}
ngOnInit() {
CHROME.runtime.sendMessage({
message: 'Give me data'
}, response => {
//...
this.changeDetectorRef.detectChanges();
});
}