在本地存储angular-cli中保存电子邮件

时间:2017-11-04 13:37:51

标签: html typescript local-storage angular-cli

所以我使用Angular CLI。我想在本地存储中保存电子邮件。我的HTML代码:

<input type="text" name="email_field" id="email"> 
<input type="submit" value="registration" onclick="save_email()">

我的类型脚本代码:

function save_email(){
    let idemail = document.getElementById('email');
    localStorage.setItem('email', this.idemail.value);
}

单击按钮后,此组件关闭,没有任何存储空间。如何解决?

2 个答案:

答案 0 :(得分:0)

首先,请勿拨打onclick,而应使用(click)角度。 其次,不要尝试从dom中获取数据,而是使用NgModel绑定。

https://stackblitz.com/edit/angular-ah8fst

答案 1 :(得分:0)

将Angular Forms用于此类内容总是好得多。

<强>模板

<form #f="ngForm" [ngFormOptions]="{updateOn: 'blur'}" novalidate>
    <label>
    <span>Email</span>
    <input
      type="email"
      name="email"
      ngModel
      placeholder="Your email">
  </label>
    <label>
    <span>Age</span>
    <input
      type="number"
      name="age"
      ngModel
      placeholder="age">
  </label>
  <button type="submit" (click)="submit(f.value)">Submit</button>
</form>

<强>组件

  submit(value){
    console.log(value);
    localStorage.setItem('data',JSON.stringify(value));
  }

相同link

的工作示例

有关template-drivendata-driven的更多内容,表示Angular