从 angular 中的输入文本字段获取值 5
Get value from Input text field in angular 5
这似乎是一个简单的问题,但我发现没有任何问题对我有用。我的 component.html:
中有一个标准输入字段
<div class="form-group">
<label>Serial</label>
<input type="text" name="serial" id="serial" [ngModel]="serial" [value]="serial" class="form-control">
</div>
所以当用户现在提交表单时,我如何获取他在字段中键入的值?如果我在我的 onSubmit()
函数中做一个简单的 console.log(this.serial)
,我什么也得不到。我在 component.ts
中声明了 serial: String;
你绑定错了。
您需要 banana-in-box 绑定 [(ngModel)]="serial"
而不是 [ngModel]="serial"
绑定中的 ()
会在每次输入更改时更新 serial
模型。从 input
到 model
单[]
如果要通过代码手动修改的话,只会绑定serial
的数据。这将导致 单向 绑定 - 从 model
到 input
.
正如您猜想的那样 - [()]
他们将双向 绑定。
这是一种绑定方式。
从视图到控制器。
文件code.component.html
<label >Code</label>
<input (input)="tcode=$event.target.value" type="text" class="form-control">
<button class="btn btn-success" (click)="submit()">Submit</button>
文件code.component.ts
tcode : string;
submit() {
console.log("the code :" + this.tcode);
}
这似乎是一个简单的问题,但我发现没有任何问题对我有用。我的 component.html:
中有一个标准输入字段<div class="form-group">
<label>Serial</label>
<input type="text" name="serial" id="serial" [ngModel]="serial" [value]="serial" class="form-control">
</div>
所以当用户现在提交表单时,我如何获取他在字段中键入的值?如果我在我的 onSubmit()
函数中做一个简单的 console.log(this.serial)
,我什么也得不到。我在 component.ts
serial: String;
你绑定错了。
您需要 banana-in-box 绑定 [(ngModel)]="serial"
而不是 [ngModel]="serial"
()
会在每次输入更改时更新 serial
模型。从 input
到 model
单[]
如果要通过代码手动修改的话,只会绑定serial
的数据。这将导致 单向 绑定 - 从 model
到 input
.
正如您猜想的那样 - [()]
他们将双向 绑定。
这是一种绑定方式。 从视图到控制器。
文件code.component.html
<label >Code</label>
<input (input)="tcode=$event.target.value" type="text" class="form-control">
<button class="btn btn-success" (click)="submit()">Submit</button>
文件code.component.ts
tcode : string;
submit() {
console.log("the code :" + this.tcode);
}