[英]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.