简体   繁体   English

Angular - ngModel 在我点击 textarea 之前不会更新

[英]Angular - ngModel not updating until I click on textarea

I have a google-chrome popup with a text box in it.我有一个带有文本框的 google-chrome 弹出窗口。 When the user types into the textbox, the text is saved into chrome local storage.当用户输入文本框时,文本被保存到 chrome 本地存储中。 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 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 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');
    });
  }

}

I am still not sure why this was happening, but it was resolved by instead using localStorage and NOT chrome.storage.local-我仍然不确定为什么会发生这种情况,但是通过使用 localStorage 而不是 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');
  }

}


You need to provide a name to your control.您需要为您的控件提供一个名称。 Try this and let me know if this works for you.试试这个,让我知道这是否适合你。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM