Javascript Angular 2 - 如何使用局部变量清除输入?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31837280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular 2 - How to clear an input with a local variable?
提问by codependent
Following the guide from the Angular2 site I have this html:
按照 Angular2 站点的指南,我有这个 html:
<input #something (keyup)="doneTyping($event)">
<button (click)="add(something .value)">Add</button>
with this controller:
使用此控制器:
@Component({
selector: 'my-app',
appInjector: [SomeService]
})
@View({
templateUrl: 'index-angular',
directives:[NgFor]
})
class MyAppComponent {
name: string;
stuff: Array<string>;
constructor(someService: SomeService) {
this.name = 'Angular2Sample';
this.stuff= someService.getStuff();
}
add(st: string){
this.stuff.push(st);
}
doneTyping($event) {
if($event.which === 13) {
this.stuff.push($event.target.value);
$event.target.value = null;
}
}
}
When the user hits enter in the input, the doneTyping method clears the input with $event.target.value = null;
.
当用户在输入中按 Enter 键时, doneTyping 方法会使用 清除输入$event.target.value = null;
。
However I can't come with a way of doing the same after pushing the button.
但是,在按下按钮后,我无法采用相同的方法。
回答by Eric Martinez
You can pass the input as a parameter in the button
您可以在按钮中将输入作为参数传递
<input #something (keyup)="doneTyping($event)">
<!-- Input as paramter -->
<button (click)="add(something)">Add</button>
And later in the add
function
后来在add
函数中
add(st: HTMLInputElement){
this.stuff.push(st.value);
st.value = null;
}
回答by Arnaud Boeglin
Also, you usually want to avoid interacting with DOM as much as possible. I just checked the Todo app example on the angular2 github and they also access the DOM element, but the last real commit is 2 months old.
此外,您通常希望尽可能避免与 DOM 交互。我刚刚检查了 angular2 github 上的 Todo 应用程序示例,他们也访问了 DOM 元素,但最后一次真正的提交是 2 个月前的。
If you use data binding you can have a cleaner code which would result in something like :
如果您使用数据绑定,您可以获得更清晰的代码,这将导致如下结果:
<input [value]="_newStuff" (keyup.enter)="addStuff()">
<button (click)="addStuff()">Add</button>
Then in your class you can just define the member _newStuff : string
, that you can implement addStuff as follow :
然后在您的课程中,您可以定义成员_newStuff : string
,您可以按如下方式实现 addStuff:
addStuff() {
this.stuff.push(_newStuff);
this._newstuff = '';
}
In most cases you might want _newStuff to be a model object that works as an interface like this :
在大多数情况下,您可能希望 _newStuff 成为一个模型对象,作为这样的接口:
class Stuff {
id : any;
property : any;
otherProperty : any;
}
And then your _newStuff would be _newStuff : Stuff;
and you could map it like this : <input [value]="_newStuff.property" (keyup.enter)="addStuff()">
.
然后你的 _newStuff 将是_newStuff : Stuff;
,你可以像这样映射它:<input [value]="_newStuff.property" (keyup.enter)="addStuff()">
。
I know your sample code is very simple and you just try to get it to work, but I believe the data binding way is more in the logic of the framework, and the Form API basically gives tools such as Control, ControlGroup and FormBuilder that help you map your model on your view with Validators and such. It would be too cumbersome on something a bit larger to access the DOM everytime you need to change the view. In the end your example is almost raw javascript executed in an Angular2 context.
我知道你的示例代码很简单,你只是试着让它工作,但我相信数据绑定的方式更多的是在框架的逻辑上,而且 Form API 基本上提供了 Control、ControlGroup 和 FormBuilder 等工具来帮助您可以使用验证器等将模型映射到视图上。每次您需要更改视图时,访问 DOM 的东西都会太麻烦。最后,您的示例几乎是在 Angular2 上下文中执行的原始 javascript。
Coming back to your example, now imagine you have another event that triggers a new stuff to be added, say a double click or so, you'd need to add another method that handles this event, passing it again the HTMLInputElement, and do basically the same thing as you do on the keyup event handler, thus duplicating code again. With data binding your component owns the state of the view and you can therefore have one simple method that won't be affected by what kind of event triggered it. There you can do the test if the model is valid ( even though for this you'd use the Form API then ).
回到您的示例,现在假设您有另一个事件触发要添加的新内容,例如双击左右,您需要添加另一个处理此事件的方法,再次将它传递给 HTMLInputElement,并且基本上执行与您在 keyup 事件处理程序上所做的相同,因此再次复制代码。通过数据绑定,您的组件拥有视图的状态,因此您可以拥有一种简单的方法,该方法不会受到触发它的事件类型的影响。如果模型有效,您可以在那里进行测试(即使为此您将使用 Form API)。
Anyways, I know this has been answered already, but I thought I would just help to improve the solution given my current understanding of it and how it could be applied to real cases.
无论如何,我知道这已经得到了回答,但我认为鉴于我目前对解决方案的理解以及如何将其应用于实际案例,我认为我只会帮助改进解决方案。
回答by Gábor Imre
You can use a one-direction bindings to access the value of the input. This is a very clear architecture; you don't have to pass DOM elements to the controller.
您可以使用单向绑定来访问输入的值。这是一个非常清晰的架构;您不必将 DOM 元素传递给控制器。
Template:
模板:
<!-- controller.value -> input.value binding-->
<input #myinput [value]=myValue>
<button (click)="done(myinput.value)">Add</button>
Controller:
控制器:
myValue: string; // If you change this then the bound input.value will also change
// be sure to import ngOnInit from @angular/common
ngOnInit() {
this.myValue = "";
}
done(newValue) {
// ... processing newValue
this.myValue = ""; // Clear the input
}
回答by Ben Perry
Here's a good way to actually get your input objects to manipulate
这是实际操作输入对象的好方法
Just need to import ViewChild from @angular/core
只需要从@angular/core 导入 ViewChild
Template:
模板:
<input #something (keyup)="doneTyping($event)">
Class:
班级:
@ViewChild("something") something : HTMLInputElement;
doneTyping(e : KeyboardEvent) {
var text = this.something.value;
if (text != "") {
//DO SOME STUFF!!!!
}
}
回答by LuDeveloper
Since version 2 of Angular is old now, and we developers are in need much more trend solutions and but we may look old topics in order to find solutions here, I felt I should mention an answer from another topic similar to this.
由于 Angular 的第 2 版现在已经过时了,我们的开发人员需要更多的趋势解决方案,但为了在此处找到解决方案,我们可能会查看旧主题,我觉得我应该提及另一个与此类似的主题的答案。
That answer works and solved my problem in Angular 7 with Type Script. Here its link
该答案有效并解决了我在 Angular 7 中使用 Type Script 的问题。这是它的链接
There are two ways:
1) I it is created with var
or let
or const
, then it cannot be deleted at all.
Example:
有两种方式: 1)我是用var
orlet
或 or创建的const
,那么就根本不能删除了。例子:
var g_a = 1; //create with var, g_a is a variable
delete g_a; //return false
console.log(g_a); //g_a is still 1
2) If it is created without var
, then it can be deleted.. as follows:
2)如果是没有创建的var
,那么可以删除..如下:
declaration:
宣言:
selectedRow: any;
selectRowOfBankForCurrentCustomer(row: any) {
this.selectedRow = row; // 'row' object is assigned.
}
deleting:
删除:
resetData(){
delete this.selectedRow; // true
console.log(this.selectedRow) // this is error because the variable deleted, not its content!!
}
回答by icer
A quick way to do it:
一个快速的方法:
<input #something (keyup)="doneTyping($event)">
<button (click)="add(something.value);something.value=''">Add</button>
A more Angular way to do it:
一种更 Angular 的方式来做到这一点:
HTML:
HTML:
<input [(ngModel)]="intermediateValue">
<button (click)="add()">Add</button>
Controller:
控制器:
intermediateValue: string;
add() {
this.doStuff(this.intermediateValue);
this.intermediateValue= "";
}