angular - Angular 表单在点击时添加输入字段
问题描述
我想在单击时添加新的输入字段,但要选择前一个输入字段上的文本以便对其进行编辑。
当我单击字段(添加工作站)时,我想选择带有(未命名工作站)的前一个字段,并且添加工作站始终可见并在下方。我一直在尝试找到一种方法来实现这一目标,但直到现在还没有运气。
html:
<div class="_form-item" *ngIf="item.type=='station'&& item.id" style="padding-top: 32px">
<div class="_label">Work Stations</div>
<div class="_ml-12 _pt-8 _flex-row" *ngFor="let work_station of item.children; let i = index;
trackBy: customTrackBy">
<input [id]="i" (ngModelChange)="updateWorkStation(i)"
[(ngModel)]="item.children[i].name"
type="text"/>
<div class="_icon-button" (click)="removeWorkStation(i)"><i
class="material-icons md-dark md-18">clear</i>
</div>
</div>
<div class="_ml-12 _pt-8 _flex-row">
<input (click)="createWorkStation()" placeholder="Add work station" [(ngModel)]="newWorkStation"
type="text"/>
<!--div class="_link-button">Add</div-->
</div>
</div>
组件功能:
createWorkStation() {
let item = new Location();
item.type = 'work_station';
item.name = 'Unnamed work station ';
item.parent = this.item.group_id;
this.service.create(item)
.map((response: Response) => <Location>response.json())
.takeWhile(() => this.alive)
.subscribe(
data => {
this.onCreateChild.emit({id: data.id});
},
err => {
console.log(err);
}
);
}
解决方案
input
您可以将模板变量 ( #test
)附加到每个字段:
<input #test [id]="i" (ngModelChange)="updateWorkStation(i)"
[(ngModel)]="item.children[i].name"
type="text"/>
使用此模板变量,您可以使用ViewChildren
它的change
Observable 来跟踪是否将新input
字段添加到视图中:
@ViewChildren('test') el: QueryList<ElementRef>;
但是,订阅change
Observable 必须在ngAfterViewInit
ngAfterViewInit() {
this.el.changes.subscribe( next => {
setTimeout(() => this.elementFocus());
});
}
elementFocus() {
if( this.el != undefined && this.el.last != undefined ) {
this.el.last.nativeElement.focus();
this.el.last.nativeElement.select();
}
}
这是一个适合您的工作示例
推荐阅读
- c# - UnityException:不允许从 MonoBehaviour 构造函数调用 GetActiveScene
- flutter - 检索 Slider 的值并将其发送到 MySQL
- angular - 无法获取活动路由参数
- android - 在 Flutter 中,如何在原生文件资源管理器中为用户打开一个文件夹,以便用户浏览其文件/文件夹
- javascript - 如何将自定义集数据传递给 src 图像“onClick”?
- css - 如何仅使用 xml 代码在 odoo 中调整二进制(64)图像的大小?(最大高度)
- java - 使用 JNDI 获取 WebSphere 完整服务器名称
- pytorch - 将 torch.nn.CrossEntropyLoss 与 label as int 和 prob 张量进行比较会产生错误
- ssh - SSH 代理转发不适用于所有 SSH 目标机器
- javascript - 从日期范围值生成新的输入字段