首页 > 解决方案 > 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);
        }
    );
}

标签: angular

解决方案


input您可以将模板变量 ( #test)附加到每个字段:

<input #test [id]="i" (ngModelChange)="updateWorkStation(i)"
       [(ngModel)]="item.children[i].name"
       type="text"/>

使用此模板变量,您可以使用ViewChildren它的changeObservable 来跟踪是否将新input字段添加到视图中:

@ViewChildren('test') el: QueryList<ElementRef>;

但是,订阅changeObservable 必须在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();
     }
  }

这是一个适合您的工作示例


推荐阅读