角形表单在单击时添加输入字段

时间:2018-09-30 12:23:36

标签: angular

我想在单击时添加新的输入字段,但要在上一个输入字段中选择文本,以便对其进行编辑。

First view of fields

Second view of fields

当我单击(添加工作站)字段时,我想使用(未命名的工作站)和“添加工作站”选择上一个字段,使其始终可见且位于下方。我一直在尝试找到一种方法来实现这一目标,但是到目前为止还算不上运气。

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);
        }
    );
}

1 个答案:

答案 0 :(得分:1)

您可以将每个模板变量(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中完成对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();
     }
  }

这是给您的working example