在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
访问,以便通过ElementRef
类的nativeElement
方法访问它们对应的DOM
元素。我已经尝试使用@ViewChild
,但它返回NgModel
类对象: @ViewChild('item_name') item_name: ElementRef;
ngAfterViewInit() {
console.log(this.item_name); // it returns NgModel class object
}
但是,我需要访问#item_name
表单字段的DOM HTMLElement
,以便在每次表单提交后重置文档焦点到#item_name
输入字段。现在,我不知道如何在不直接访问DOM的情况下进行操作,也不想通过DOM api直接访问DOM。
如果能得到帮助,我会很高兴的。