TypeError:无法使用@ViewChild读取未定义的属性“ nativeElement”?

时间:2019-06-08 16:33:22

标签: javascript angular7

我正在Angular-7上开发项目,并使用如何使用@ViewChild直接从TypeScript文件访问元素。但是我正在错误以下。在我看来,@ViewChild('serverContentInput', { read: true, static: true }) serverContentInput: ElementRef; 没有通过@ViewChild获得对模板和DOM的访问权限

错误:

ERROR TypeError: Cannot read property 'nativeElement' of undefined
    at CockpitComponent.onAddServer (cockpit.component.ts:24)
    at Object.eval [as handleEvent] (CockpitComponent.html:11)
    at handleEvent (core.js:34777)
    at callWithDebugContext (core.js:36395)
    at Object.debugHandleEvent [as handleEvent] (core.js:36031)
    at dispatchEvent (core.js:22519)
    at core.js:33709
    at HTMLButtonElement.<anonymous> (platform-browser.js:1789)
    at ZoneDelegate.invokeTask (zone-evergreen.js:391)
    at Object.onInvokeTask (core.js:30873)

cockpit.component.ts

import { Component, OnInit, EventEmitter, Output, ViewChild, ElementRef, Directive } from '@angular/core';

@Component({
  selector: 'app-cockpit',
  templateUrl: './cockpit.component.html',
  styleUrls: ['./cockpit.component.css']
})
export class CockpitComponent implements OnInit {
  @Output() serverCreated = new EventEmitter<{ serverName: string, serverContent: string }>();
  @Output('bpCreated') blueprintCreated = new EventEmitter<{ serverName: string, serverContent: string }>();

  // newServerName = '';
  // newServerContent = '';
  @ViewChild('serverContentInput', { read: true, static: false }) serverContentInput: ElementRef;

  constructor() { }

  ngOnInit() {
  }

  onAddServer(nameInput: HTMLInputElement) {
    this.serverCreated.emit({
      serverName: nameInput.value,
      serverContent: this.serverContentInput.nativeElement.value
    });
  }

  onAddBlueprint(nameInput: HTMLInputElement) {
    this.blueprintCreated.emit({
      serverName: nameInput.value,
      serverContent: this.serverContentInput.nativeElement.value
    });
  }
}

cockpit.component.html

<div class="row">
  <div class="col-xs-12">
    <p>Add new servers or blueprint !</p>
    <label>Server Name</label>
    <!-- <input type="text" class="form-control" [(ngModel)]="newServerName" /> -->
    <input type="text" class="form-control" #serverNameInput />  <!-- Local Reference -->
    <label>Server Content</label>
    <!-- <input type="text" class="form-control" [(ngModel)]="newServerContent" /> -->
    <input type="text" class="form-control" #serverContentInput  />
    <br>
    <button class="btn btn-primary" (click)="onAddServer(serverNameInput)">Add Server</button>
    <button class="btn btn-primary" (click)="onAddBlueprint(serverNameInput)">Add Server Blueprint</button>
  </div>
</div>

1 个答案:

答案 0 :(得分:0)

属性read告诉Angular 要读什么。可以省略以读取任何默认值。

因此,在您的情况下,两者都应该起作用:

@ViewChild('serverContentInput', { read: ElementRef, static: false })
@ViewChild('serverContentInput', { static: false })