Angular: 将事件添加到 FormArray 中动态添加的 FormControls
Angular: Adding events to FormControls added dynamically in FormArray
我正在使用 Angular 4
并且正在创建一个页面,用户可以在其中创建由散列、序列和常量值组成的格式。用户可以按任何顺序添加它们,因此为此我使用 FormArray
动态创建它们
HTML 代码为:
<div formArrayName="components"
*ngFor="let c of components.controls; let i=index">
<div [formGroupName]="i">
<div class="form-group row">
<div class="col-md-3">
<select type="" id="component" class="form-control" placeholder=""
formControlName="component">
<option value="Sequence">Sequence</option>
<option value="Hash">Hash</option>
<option value="Constant">Constant</option>
</select>
</div>
<div class="col-md-2">
<input type="number" class="form-control" formControlName="limit" />
</div>
<div class="col-md-4">
<input type="text" class="form-control" formControlName="value" />
</div>
<div class="col-md-2" style="color:red" (click)="deleteRow(i)">
<fa name="times"></fa>
</div>
</div>
</div>
</div>
上面的代码会产生这样的输出。
问题这些动态创建的控件如何绑定事件?例如,在下拉列表中选择某个值时,我想隐藏它旁边的输入控件。
您可以将事件绑定到采用索引的函数,然后使用索引从函数中的 formArray 检索控件
在你的HTML
<select type="" id="component" class="form-control" placeholder=""
formControlName="component" (change)="onChange(i)>
在你的 ts 文件中
let row = components.controls[pos] as FormGroup
//row now contains all the controls bound to it you can access the controls like the following
let value = row.controls["component"].value
或者,如果您只是想在没有任何复杂条件的情况下隐藏输入,您可以在 HTML
中尝试此操作
<input type="number" class="form-control" formControlName="limit" *ngIf="c.get('component').value != 'whatever'"/>
我正在使用 Angular 4
并且正在创建一个页面,用户可以在其中创建由散列、序列和常量值组成的格式。用户可以按任何顺序添加它们,因此为此我使用 FormArray
HTML 代码为:
<div formArrayName="components"
*ngFor="let c of components.controls; let i=index">
<div [formGroupName]="i">
<div class="form-group row">
<div class="col-md-3">
<select type="" id="component" class="form-control" placeholder=""
formControlName="component">
<option value="Sequence">Sequence</option>
<option value="Hash">Hash</option>
<option value="Constant">Constant</option>
</select>
</div>
<div class="col-md-2">
<input type="number" class="form-control" formControlName="limit" />
</div>
<div class="col-md-4">
<input type="text" class="form-control" formControlName="value" />
</div>
<div class="col-md-2" style="color:red" (click)="deleteRow(i)">
<fa name="times"></fa>
</div>
</div>
</div>
</div>
上面的代码会产生这样的输出。
问题这些动态创建的控件如何绑定事件?例如,在下拉列表中选择某个值时,我想隐藏它旁边的输入控件。
您可以将事件绑定到采用索引的函数,然后使用索引从函数中的 formArray 检索控件
在你的HTML
<select type="" id="component" class="form-control" placeholder=""
formControlName="component" (change)="onChange(i)>
在你的 ts 文件中
let row = components.controls[pos] as FormGroup
//row now contains all the controls bound to it you can access the controls like the following
let value = row.controls["component"].value
或者,如果您只是想在没有任何复杂条件的情况下隐藏输入,您可以在 HTML
中尝试此操作 <input type="number" class="form-control" formControlName="limit" *ngIf="c.get('component').value != 'whatever'"/>