使用 Angular 6 设置输入字段的值



我在使用 Angular 设置输入元素的值时遇到了一些麻烦。

我正在尝试通过此方法在我的应用程序中设置动态创建的输入元素的值:

copyPricingToAll(): void {
var copyValue: string = document.getElementById("priceInputGlobal").value;
this.currentItem.orderLines.forEach(orderLine => {
document.getElementById("priceInput-" + orderLine.id).setAttribute("value", copyValue);
});
}

我正在创建这样的行:

<ng-container *ngFor="let orderLine of currentItem.orderLines let i=index">
<tr>
<td>{{getCorrectTimeString(orderLine)}}</td>
<td>{{orderLine.quantity}}</td>
<td><input id="priceInput-{{orderLine.id}}" type="number" value="{{orderLine.price}}"></td>
</tr>
</ng-container>

很遗憾,.value 未被识别为有效操作。我不确定如何在角度中正确设置动态创建的元素的值。我希望有人能够帮助我解决这个问题。

您应该使用以下方法:

<td><input id="priceInput-{{orderLine.id}}" type="number" [(ngModel)]="orderLine.price"></td>

您需要将FormsModule添加到imports部分中的app.module中,如下所示:

import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [
...
],
imports: [
BrowserModule,
FormsModule
],
..

ngModel两边括号的使用如下:

  • []显示它正在从您的 TS 文件中获取输入。 此输入应为公共成员变量。 从 TS 到 HTML 的单向绑定。

  • ()显示它正在将 HTML 文件的输出带到 TS 文件中的变量。 从 HTML 到 TS 的单向绑定。

  • [()]两者都是(例如双向绑定(

有关更多信息,请参阅此处: https://angular.io/guide/template-syntax

我还建议用类似这样的东西替换id="priceInput-{{orderLine.id}}"[id]="getElementId(orderLine)"其中getElementId(orderLine)返回 TS 文件中的元素 Id,并且可以在您需要引用该元素的任何情况下使用(以避免简单的错误,例如在一个地方调用它priceInput1,在另一个地方priceInput-1(如果您仍然需要在其他地方通过它的 Id 访问输入(。

作为替代方案,您可以使用响应式表单。下面是一个示例:https://stackblitz.com/edit/angular-pqb2xx

模板

<form [formGroup]="mainForm" ng-submit="submitForm()">
Global Price: <input type="number" formControlName="globalPrice">
<button type="button" [disabled]="mainForm.get('globalPrice').value === null" (click)="applyPriceToAll()">Apply to all</button>
<table border formArrayName="orderLines">
<ng-container *ngFor="let orderLine of orderLines let i=index" [formGroupName]="i">
<tr>
<td>{{orderLine.time | date}}</td>
<td>{{orderLine.quantity}}</td>
<td><input formControlName="price" type="number"></td>
</tr>
</ng-container>
</table>
</form>

元件

import { Component } from '@angular/core';
import { FormGroup, FormControl, FormArray } from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
name = 'Angular 6';
mainForm: FormGroup;
orderLines = [
{price: 10, time: new Date(), quantity: 2},
{price: 20, time: new Date(), quantity: 3},
{price: 30, time: new Date(), quantity: 3},
{price: 40, time: new Date(), quantity: 5}
]
constructor() {
this.mainForm = this.getForm();
}
getForm(): FormGroup {
return new FormGroup({
globalPrice: new FormControl(),
orderLines: new FormArray(this.orderLines.map(this.getFormGroupForLine))
})
}
getFormGroupForLine(orderLine: any): FormGroup {
return new FormGroup({
price: new FormControl(orderLine.price)
})
}
applyPriceToAll() {
const formLines = this.mainForm.get('orderLines') as FormArray;
const globalPrice = this.mainForm.get('globalPrice').value;
formLines.controls.forEach(control => control.get('price').setValue(globalPrice));
// optionally recheck value and validity without emit event.
}
submitForm() {
}
}

您可以使用 3 种方式。他们是,

1( 使用 ngModel

<input placeholder="Search..." autocomplete="off" [(ngModel)]="customSearch"/>
customSearch: string;
this.customSearch: string = "";

2( 使用表单控件名称

<form [formGroup]="searchForm">
<input placeholder="Search..." autocomplete="off" formControlName="customSearch"/></form>
this.searchForm = this._fb.group({
'customSearch': ['']
});
this.searchForm.controls['customSearch'].setValue('');
let val = this.searchForm.value.customSearch;

3( 使用 ElementRef

<input placeholder="Search..." autocomplete="off" #customSearch />
@ViewChild('customSearch', { static: true }) customSearchElement: ElementRef;
this.customSearchElement.nativeElement.value = "";
let test : any = document.getElementById("test") as HTMLInputElement | null
test.value = spaceNotes

这是另一种方法。

最新更新