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

Ben*_*ins 29 viewchild angular

我正在尝试访问本机元素,以便在单击另一个元素时专注于它(非常类似于html属性"for" - 因为不能在此类型的元素上使用.

但是我得到错误:

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

我尝试console.log中的nativeElement,ngAfterViewInit()以便它被加载,但它仍然会抛出错误.

我还在click事件处理程序中访问nativeElement,这样我可以在单击另一个元素时聚焦该元素 - 这可能是什么在混淆它,因为它在视图加载之前编译?

例如:

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

focusKeywordsInput(){
    this.keywordsInput.nativeElement.focus();
}
Run Code Online (Sandbox Code Playgroud)

完整代码:

正在使用的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>
Run Code Online (Sandbox Code Playgroud)

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);
   }
}
Run Code Online (Sandbox Code Playgroud)

完整的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>
Run Code Online (Sandbox Code Playgroud)

Gün*_*uer 38

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

id="keywords-input"
Run Code Online (Sandbox Code Playgroud)

应该是一个模板变量:

#keywordsInput
Run Code Online (Sandbox Code Playgroud)

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

@ViewChild() 支持模板变量的名称为string:

@ViewChild('keywordsInput') keywordsInput;
Run Code Online (Sandbox Code Playgroud)

或组件或指令类型:

@ViewChild(MyKeywordsInputComponent) keywordsInput;
Run Code Online (Sandbox Code Playgroud)

另请参见/sf/answers/2464677701/

提示:
keywordsInputngAfterViewInit()调用之前未设置

  • 使用ngAfterViewInit()完成了任务! (2认同)

use*_*861 21

如果目标元素位于隐藏元素内,您也会收到此错误.如果这是您的HTML:

<div *ngIf="false">
    <span #sp>Hello World</span>
</div>
Run Code Online (Sandbox Code Playgroud)

你的@ViewChild('sp') sp意志不明确.

在这种情况下,则不要使用*ngIf.

而是使用类来显示/隐藏隐藏的元素.

<div [class.show]="shouldShow">...</div>
Run Code Online (Sandbox Code Playgroud)


Pra*_*eek 13

接受的答案在所有方面都是正确的,在我无法在我的应用程序组件之一中呈现 Google 地图后,我偶然发现了这个线程。

现在,如果您使用的是最近的 angular 版本,即 7+ 的 angular,那么您将不得不处理以下ViewChild声明,即

@ViewChild(selector: string | Function | Type<any>, opts: {
read?: any;
static: boolean;
})
Run Code Online (Sandbox Code Playgroud)

现在,有趣的部分是静态值,根据定义,

  • static - 在更改检测运行之前解析查询结果为真

现在为了渲染地图,我使用了以下内容,

@ViewChild('map', { static: true }) mapElement: any;
  map: google.maps.Map;
Run Code Online (Sandbox Code Playgroud)


Fel*_*ler 13

我遇到了类似的问题,但就我而言,我试图阅读方法nativeElement内部ngOnInit

@ViewChild('userNameInput') userNameInput: ElementRef<HTMLInputElement>;
...
ngOnInit(): void {
    this.userNameInput.nativeElement.focus();
}
Run Code Online (Sandbox Code Playgroud)

我已经更改为ngAfterViewInit并且一切正常:

@ViewChild('userNameInput') userNameInput: ElementRef<HTMLInputElement>;
...
ngAfterViewInit(): void {
    this.userNameInput.nativeElement.focus();
}
Run Code Online (Sandbox Code Playgroud)


小智 6

当您尝试定位包含在条件中的元素时,会发生此错误。

所以,在这里,如果我使用 ngIf 代替 [hidden],它会给我 TypeError: Cannot read property 'nativeElement' of undefined

所以使用 [hidden]、class.show 或 class.hide 代替 *ngIf。

<button (click)="displayMap()" class="btn btn-primary">Display Map</button>

   <div [hidden]="!display">
      <div #mapContainer id="map">Content to render when condition is true.</div>
   </div>
Run Code Online (Sandbox Code Playgroud)