如何从Angular 4 +中的NgForm中的NgModel FormControl获取ElementRef引用

时间:2017-11-28 20:42:45

标签: javascript angular angular-forms angular4-forms

在Angular 4+中,我遵循模板驱动形式:

<form #addForm="ngForm" (ngSubmit)="onFormSubmit($event, addForm)" >
  <div class="form-group">
    <label for="item_name">Item Name</label>
    <input id="item_name" name="item_name" [(ngModel)]="itemName" 
          #item_name="ngModel" autofocus class="form-control"
          required minlength="4" maxlength="20" 
          aria-describedby="itemNameHelpBlock">
    <small *ngIf="(item_name.invalid && item_name.touched)" id="itemNameHelpBlock" class="form-text text-error" >
      Value must be at least 4 characters and must not exceed 20 characters
    </small>
  </div>
  <div class="form-group">
    <label for="item_type">Item Type</label>
    <input id="item_type" name="item_type" [(ngModel)]="itemType" 
         #item_type="ngModel" class="form-control" required minlength="2"
          maxlength="20" aria-describedby="itemTypeHelpBlock">
    <small *ngIf="(item_type.invalid && item_type.touched)" id="itemTypeHelpBlock" class="form-text text-error" >
      Value must be at least 2 characters and must not exceed 20 characters
    </small>
  </div>
  <button class="btn btn-output-primary btn-lg" [disabled]="!addForm.form.valid">Add</button>
</form>

在组件部分中,我想要将表单字段(即item_nameitem_type)作为ElementRef进行访问,以便我可以通过以下方式访问相应的DOM元素nativeElement类的ElementRef方法。

我已尝试使用@ViewChild,但它会返回NgModel类对象:

  @ViewChild('item_name') item_name: ElementRef;

  ngAfterViewInit() {
    console.log(this.item_name); // it returns NgModel class object
  }

但是,我需要访问HTMLElement表单字段的DOM #item_name,这样我才能在每个表单提交后将文档焦点重置为#item_name输入字段。现在,我不知道如何在不直接访问DOM的情况下做到这一点,我也不想通过DOM api直接访问DOM。

如果我在这里得到一些帮助,我会很高兴。

1 个答案:

答案 0 :(得分:8)

我只需将read选项添加到ViewChild查询:

@ViewChild('item_name', { read: ElementRef }) item_name: ElementRef;
                           ^^^^^^^^^^^^^^^

<强> Stackblitz Example

另见

相关问题