【发布时间】:2018-05-12 10:38:39
【问题描述】:
在 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>
在组件部分,我想以ElementRef访问表单字段(即item_name,item_type),这样我就可以通过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。
如果我能在这里得到一些帮助,我会很高兴。
【问题讨论】:
标签: javascript angular angular-forms angular4-forms