繁体   English   中英

当我单击 Angular 中的按钮时,如何在输入字段中输入我写的内容?

[英]How to type out what I write in input field when I click a button in Angular?

所以我想在输入文本字段中写一些东西,然后按下按钮并在此处显示<p>Hello {{inputValue}}</p> 我不想为此使用 keyup。 我也将它保存在 localstorage 中,它现在可以工作,但如果我删除 keyup 就不行了。

我的 .ts 文件:

  selector: 'app-dialouge',
  templateUrl: './dialouge.component.html',
  styleUrls: ['./dialouge.component.css']
})

export class DialougeComponent implements OnInit {
  inputValue: string;
  onKeyUp(event){
    this.inputValue = event.target.value;
  }

  saveBtn(): void {
    console.log("btn clicked: " + this.inputValue);
    window.localStorage.setItem("inputValue", this.inputValue);
    window.localStorage.getItem("inputValue");
  };
  clearStorage(){
    localStorage.clear();
    console.log("ls cleared");
  }


  constructor() { }

  ngOnInit(): void {

  }

}

我的模板文件:

<input type="text" (keyup)="onKeyUp($event)" />
<button (click)="saveBtn()">save</button>
<button (click)="clearStorage()">clear</button>

<p>Hello {{inputValue}}</p>

您可以在input使用ngModel而不是keyup

像下面一样改变你的 HTML,

<input type="text" [(ngModel)]="inputValue" />
<button (click)="saveBtn()">save</button>
<button (click)="clearStorage()">clear</button>

<p>Hello {{inputValue}}</p>

从 ts 文件中删除onKeyUp方法。

您应该使用[(ngModel)]input更改它,因为使用[(ngModel)]更合适。 当您从键盘上松开手指时, keyup会触发。

<input type="text" [(ngModel)]="inputValue" />
<button (click)="saveBtn()">save</button>
<button (click)="clearStorage()">clear</button>

<p>Hello {{afterButtonPressedValue}}</p>

创建另一个值显示和输入: inputValue用于打字和afterButtonPressedValue在模板显示。

你的 ts 将是:

  selector: 'app-dialouge',
  templateUrl: './dialouge.component.html',
  styleUrls: ['./dialouge.component.css']
})

export class DialougeComponent implements OnInit {
  inputValue: string;
  afterButtonPressedValue = '';

  saveBtn(): void {
    console.log("btn clicked: " + this.inputValue);
    window.localStorage.setItem("inputValue", this.inputValue);
    window.localStorage.getItem("inputValue");
    this.afterButtonPressedValue = this.inputValue;
  };
  clearStorage(){
    localStorage.clear();
    console.log("ls cleared");
    this.afterButtonPressedValue = '';
  }


  constructor() { }

  ngOnInit(): void {

  }

}

暂无
暂无

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

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