Search code examples
javascriptangulartypescriptgoogle-chromegoogle-chrome-extension

Angular - ngModel not updating until I click on textarea


I have a google-chrome popup with a text box in it. When the user types into the textbox, the text is saved into chrome local storage. When the popup is closed and then reopened, the text box is supposed to autofill with the last text that was saved. It is working perfectly, except when I close and open the popup, the text field appears to be empty and does not autofill until I click on the text field. I know that the value is changed right when the popup opens because it is logging to the console, I just can't see the change until after I click. Any Idea what I am doing wrong?

app.componenet.html

<div>

  <mat-form-field>
    <mat-label>Input</mat-label>
    <textarea matInput [(ngModel)]='myText' (ngModelChange)="saveChanges()"></textarea>
  </mat-form-field>

</div>

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  ngOnInit() {this.restore()};

  title = 'dataStoreTest';
  myText = '';

  saveChanges() {
    chrome.storage.local.set({storedText: this.myText});
    console.log('save');
  }

  restore(){
    let self = this;
    chrome.storage.local.get( ['storedText'], function(result){
      self.myText = result.storedText;
      console.log(result.storedText +' Was restored');
    });
  }

}


Solution

  • I am still not sure why this was happening, but it was resolved by instead using localStorage and NOT chrome.storage.local-

    the fixed code -

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      ngOnInit() {this.restore()};
    
      title = 'dataStoreTest';
      myText = '';
    
      saveChanges() {
        localStorage.setItem('storedText', this.myText);
        console.log('save');
      }
    
      restore(){
          this.myText = localStorage.getItem('storedText');
          console.log(localStorage.getItem('storedText') +' Was restored');
      }
    
    }