@viewChild不起作用-无法读取未定义的属性nativeElement

本杰明·巴金斯(Benjamin Baggins)

我正在尝试访问本机元素,以便在单击另一个元素时专注于本机元素(非常类似于html属性“ for”-for不能在这种类型的元素上使用。

但是我得到了错误:

TypeError:无法读取未定义的属性“ nativeElement”

我尝试在console.log中输入nativeElement,ngAfterViewInit()以便加载它,但仍然会引发错误。

我还可以在click事件处理程序中访问nativeElement,以便在单击另一个元素时可以将元素聚焦-这可能是对它进行处理的原因,因为它在加载视图之前就已经编译了?

例如:

ngAfterViewInit() {
    console.log(this.keywordsInput.nativeElement); // throws an error
}

focusKeywordsInput(){
    this.keywordsInput.nativeElement.focus();
}

完整代码:

所使用的html模板的相关部分:

<div id="keywords-button" class="form-group" (click)="focusKeywordsInput()">
    <input formControlName="keywords" id="keywords-input" placeholder="KEYWORDS (optional)"/>
    <div class="form-control-icon" id="keywords-icon"></div>
</div>

component.ts:

import { Component, OnInit, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
import {  REACTIVE_FORM_DIRECTIVES, 
          FormGroup, 
          FormBuilder, 
          Validators,
          ControlValueAccessor
        } from '@angular/forms';
import { NumberPickerComponent } from './number-picker.component';
import { DistanceUnitsComponent } from './distance-units.component';
import { MapDemoComponent } from '../shared/map-demo.component';
import { AreaComponent } from './area-picker.component';
import { GoComponent } from './go.component';
import { HighlightDirective } from '../highlight.directive';

@Component({
   selector: 'find-form',
   templateUrl: 'app/find-page/find-form.component.html',
   styleUrls: ['app/find-page/find-form.component.css'],
   directives: [REACTIVE_FORM_DIRECTIVES, 
                NumberPickerComponent, 
                DistanceUnitsComponent, 
                MapDemoComponent, 
                AreaComponent, 
                GoComponent]
})
export class FindFormComponent implements OnInit, AfterViewInit {
   findForm: FormGroup;
   submitted: boolean; // keep track on whether form is submitted
   events: any[] = []; // use later to display form changes
   @ViewChild('keywords-input') keywordsInput;
//comment
   constructor(private formBuilder: FormBuilder, el: ElementRef) {}

   ngOnInit() {
      this.findForm = this.formBuilder.group({
         firstname: ['', [ Validators.required, Validators.minLength(5) ] ],
         lastname: ['', Validators.required],
         keywords: [],
         area: ['', Validators.required],
         address: this.formBuilder.group({
            street: [],
            zip: [],
            city: []
         })
      });

      this.findForm.valueChanges.subscribe(data => console.log('form changes', data));
   }

     ngAfterViewInit() {
    console.log(this.keywordsInput.nativeElement); // throws an error
  }

   focusKeywordsInput(){
      this.keywordsInput.nativeElement.focus();
   }

   save(isValid: boolean) {
      this.submitted = true;
      // check if model is valid
      // if valid, call API to save customer
      console.log(isValid);
   }
}

完整的html模板(可能不相关):

<form class="text-uppercase" [formGroup]="findForm" (ngSubmit)="save(findForm.value, findForm.valid)">
    <div class="row is-heading">
        <div class="col-sm-8 offset-sm-2 col-md-6 offset-md-3 col-lg-4 offset-lg-4 input-group">
            <h2 class="search-filter-heading heading m-x-auto">find vegan</h2>
        </div>
    </div>
    <div class="row has-error-text">
        <div class="col-sm-8 offset-sm-2 col-md-6 offset-md-3 col-lg-4 offset-lg-4 input-group btn-group" style="height:64px;">
            <div style="position: relative; display: inline-block; width: 100%;">
                <multiselect #multiselect></multiselect>
            </div>
        </div>
    </div>
    <div class="row error-text"  [style.display]="multiselect.selectedCategories.length < 1 && submitted ? 'block' : 'none'">
        <div class="col-sm-8 offset-sm-2 col-md-6 offset-md-3 col-lg-4 offset-lg-4 form-group input-group btn-group">
            <small>Please select at least 1 category.</small>
        </div>
    </div>
    <div class="row is-heading">
        <div class="col-sm-8 offset-sm-2 col-md-6 offset-md-3 col-lg-4 offset-lg-4 input-group">
            <h2 class="search-filter-heading heading m-x-auto">within</h2>
        </div>
    </div>
    <div class="row">
        <div class="col-sm-8 offset-sm-2 col-md-6 offset-md-3 col-lg-4 offset-lg-4 input-group btn-group" style="height:64px;">
            <div style="position: relative; display: inline-block;">
                <number-picker #numberPicker></number-picker>
            </div>
            <distance-units></distance-units>
        </div>
    </div>
    <div class="row is-heading">
        <div class="col-sm-8 offset-sm-2 col-md-6 offset-md-3 col-lg-4 offset-lg-4 input-group">
            <h2 class="search-filter-heading heading m-x-auto">of</h2>
        </div>
    </div>
    <div class="row has-error-text">
        <div class="col-sm-8 offset-sm-2 col-md-6 offset-md-3 col-lg-4 offset-lg-4 input-group btn-group" style="height:64px;">
            <div style="position: relative; display: inline-block; width: 100%;">
                <my-area></my-area>
            </div>
        </div>
    </div>
    <div class="row error-text"  [style.display]="multiselect.selectedCategories.length < 1 && submitted ? 'block' : 'none'">
        <div class="col-sm-8 offset-sm-2 col-md-6 offset-md-3 col-lg-4 offset-lg-4 form-group input-group btn-group">
            <small [hidden]="findForm.controls.firstname.valid || (findForm.controls.firstname.pristine && !submitted)">Please enter an area.</small>
        </div>
    </div>
    <div class="row is-heading">
        <div class="col-sm-8 offset-sm-2 col-md-6 offset-md-3 col-lg-4 offset-lg-4 input-group">
            <h2 class="search-filter-heading heading m-x-auto">keywords</h2>
        </div>
    </div>
    <div class="row form-group">
        <div class="col-sm-8 offset-sm-2 col-md-6 offset-md-3 col-lg-4 offset-lg-4 input-group btn-group" style="height:64px;">
            <div style="position: relative; display: inline-block; width: 100%;">
                <div id="keywords-button" class="form-group" (click)="focusKeywordsInput()">
                    <input formControlName="keywords" id="keywords-input" placeholder="KEYWORDS (optional)"/>
                    <div class="form-control-icon" id="keywords-icon"></div>
                </div>
            </div>
        </div>
    </div>
    <div class="row">
        <div class="col-sm-8 offset-sm-2 col-md-6 offset-md-3 col-lg-4 offset-lg-4 input-group btn-group" style="height:64px;">
            <div style="position: relative; display: inline-block; width: 100%;">
                <go></go>
            </div>
        </div>
    </div>
</form>
贡特·佐赫鲍尔(GünterZöchbauer)

@ViewChild('keywords-input') keywordsInput; 不匹配 id="keywords-input"

id="keywords-input"

应该是一个模板变量:

#keywordsInput

请注意,应使用驼峰式大小写,因为-模板引用名称中不允许使用这种情况

@ViewChild() 支持模板变量的名称为字符串:

@ViewChild('keywordsInput') keywordsInput;

或组件或指令类型:

@ViewChild(MyKeywordsInputComponent) keywordsInput;

另请参阅https://stackoverflow.com/a/35209681/217408

提示:
keywordsInput未设置之前ngAfterViewInit()被调用

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

Angular 2 ViewChild不起作用-无法读取未定义的属性nativeElement

来自分类Dev

如何解决使用ViewChild ElementRef时无法读取angular中未定义的属性'nativeElement'

来自分类Dev

.hasPermissions 不起作用?类型错误:无法读取未定义客户端的属性?

来自分类Dev

电子遥控器(关闭,最小化等)不起作用(无法读取未定义的属性“ getCurrentWindow”)

来自分类Dev

CodeIgniter 未定义的属性加载不起作用

来自分类Dev

当您使用“ @ViewChild”中的信息时,如何避免“ ExpressionChangedAfterItHasBeenCheckedError”或“无法读取未定义的属性”?

来自分类Dev

如何制作手风琴不起作用,并告诉我如果元素存在,则无法读取未定义的属性“ classList”?

来自分类Dev

BackgroundGeolocation 不起作用,未定义

来自分类Dev

读取()不起作用

来自分类Dev

当属性未定义时,Angularjs过滤器不起作用

来自分类Dev

使用异步不起作用$未定义

来自分类Dev

检查变量是否未定义不起作用

来自分类Dev

phonegap插件不起作用-连接未定义

来自分类Dev

clearInterval不起作用,间隔未定义

来自分类Dev

Promise在Javascript中不起作用,返回未定义

来自分类Dev

HTML DOM不起作用/返回未定义

来自分类Dev

使用异步不起作用$未定义

来自分类Dev

Javascript,如果未定义不起作用

来自分类Dev

Jquery未定义条件不起作用

来自分类Dev

Node 中的 Promise 不起作用 - .then 未定义

来自分类Dev

perl“ do”起作用“ require”不起作用:未定义的子例程

来自分类Dev

蓝鸟承诺`promisifyAll`不起作用-无法读取属性'then'

来自分类Dev

读取SimpleXML元素属性不起作用

来自分类Dev

读取RDF不起作用

来自分类Dev

onsubmit属性不起作用

来自分类Dev

粗体属性不起作用

来自分类Dev

属性设置不起作用

来自分类Dev

背景属性不起作用

来自分类Dev

AllowHtml属性不起作用

Related 相关文章

  1. 1

    Angular 2 ViewChild不起作用-无法读取未定义的属性nativeElement

  2. 2

    如何解决使用ViewChild ElementRef时无法读取angular中未定义的属性'nativeElement'

  3. 3

    .hasPermissions 不起作用?类型错误:无法读取未定义客户端的属性?

  4. 4

    电子遥控器(关闭,最小化等)不起作用(无法读取未定义的属性“ getCurrentWindow”)

  5. 5

    CodeIgniter 未定义的属性加载不起作用

  6. 6

    当您使用“ @ViewChild”中的信息时,如何避免“ ExpressionChangedAfterItHasBeenCheckedError”或“无法读取未定义的属性”?

  7. 7

    如何制作手风琴不起作用,并告诉我如果元素存在,则无法读取未定义的属性“ classList”?

  8. 8

    BackgroundGeolocation 不起作用,未定义

  9. 9

    读取()不起作用

  10. 10

    当属性未定义时,Angularjs过滤器不起作用

  11. 11

    使用异步不起作用$未定义

  12. 12

    检查变量是否未定义不起作用

  13. 13

    phonegap插件不起作用-连接未定义

  14. 14

    clearInterval不起作用,间隔未定义

  15. 15

    Promise在Javascript中不起作用,返回未定义

  16. 16

    HTML DOM不起作用/返回未定义

  17. 17

    使用异步不起作用$未定义

  18. 18

    Javascript,如果未定义不起作用

  19. 19

    Jquery未定义条件不起作用

  20. 20

    Node 中的 Promise 不起作用 - .then 未定义

  21. 21

    perl“ do”起作用“ require”不起作用:未定义的子例程

  22. 22

    蓝鸟承诺`promisifyAll`不起作用-无法读取属性'then'

  23. 23

    读取SimpleXML元素属性不起作用

  24. 24

    读取RDF不起作用

  25. 25

    onsubmit属性不起作用

  26. 26

    粗体属性不起作用

  27. 27

    属性设置不起作用

  28. 28

    背景属性不起作用

  29. 29

    AllowHtml属性不起作用

热门标签

归档