在 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_name
的形式访问表单字段(即 item_type
、 ElementRef
)这样我就可以访问他们对应的DOM
元素通过nativeElement
ElementRef
的方法类(class)。我试过
@ViewChild
但是,它返回 NgModel
类对象: @ViewChild('item_name') item_name: ElementRef;
ngAfterViewInit() {
console.log(this.item_name); // it returns NgModel class object
}
但是,我需要访问 DOM
HTMLElement
的 #item_name
表单字段,以便我可以将文档焦点重置为 #item_name
每次提交表单后的输入字段。现在,我不知道如何在不直接访问 DOM 的情况下做到这一点,而且我不想通过 DOM api 直接访问 DOM。如果我能在这里得到一些帮助,我会很高兴。
最佳答案
我会简单地添加 read
ViewChild
的选项询问:
@ViewChild('item_name', { read: ElementRef }) item_name: ElementRef;
^^^^^^^^^^^^^^^
Stackblitz Example
也可以看看
关于javascript - 如何在 Angular 4+ 中从 NgForm 中的 NgModel FormControl 获取 ElementRef 引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47540610/