[英]How to type out what I write in input field when I click a button in Angular?
So I want to write something in the input textfield and then press the button and show it here <p>Hello {{inputValue}}</p>
.所以我想在输入文本字段中写一些东西,然后按下按钮并在此处显示
<p>Hello {{inputValue}}</p>
。 I DO NOT want to use keyup for this.我不想为此使用 keyup。 I am also saving it in localstorage which works right now but not if I remove keyup.
我也将它保存在 localstorage 中,它现在可以工作,但如果我删除 keyup 就不行了。
My .ts file:我的 .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 {
}
}
my template file:我的模板文件:
<input type="text" (keyup)="onKeyUp($event)" />
<button (click)="saveBtn()">save</button>
<button (click)="clearStorage()">clear</button>
<p>Hello {{inputValue}}</p>
You can use ngModel
instead of keyup
into input
.您可以在
input
使用ngModel
而不是keyup
。
change your HTML like below,像下面一样改变你的 HTML,
<input type="text" [(ngModel)]="inputValue" />
<button (click)="saveBtn()">save</button>
<button (click)="clearStorage()">clear</button>
<p>Hello {{inputValue}}</p>
Remove onKeyUp
method from your ts file.从 ts 文件中删除
onKeyUp
方法。
You should use [(ngModel)]
to change it with input
, because it's more proper to use [(ngModel)]
.您应该使用
[(ngModel)]
用input
更改它,因为使用[(ngModel)]
更合适。 keyup
fires when you released your finger from keyboard.当您从键盘上松开手指时,
keyup
会触发。
<input type="text" [(ngModel)]="inputValue" />
<button (click)="saveBtn()">save</button>
<button (click)="clearStorage()">clear</button>
<p>Hello {{afterButtonPressedValue}}</p>
Create another value to show and type: inputValue
for typing and afterButtonPressedValue
for showing in template.创建另一个值显示和输入:
inputValue
用于打字和afterButtonPressedValue
在模板显示。
And your ts will be:你的 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.