Ошибка типа: Не удается прочитать свойство 'nativeElement' из неопределенного с @ViewChild? - PullRequest
0 голосов
/ 08 июня 2019

Я разрабатываю проект на Angular-7 и использую то, как вы также можете получить доступ к вашим элементам напрямую из файла TypeScript с помощью @ViewChild.Но я получаю ниже ошибки.Мне кажется, что @ViewChild('serverContentInput', { read: true, static: true }) serverContentInput: ElementRef; не получает доступ к шаблону и DOM с @ ViewChild

Ошибка:

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 голосов
/ 09 июня 2019

Свойство read сообщает Angular , что читать. Может быть опущено, чтобы прочитать все, что по умолчанию.

Так что в вашем случае либо должно работать:

@ViewChild('serverContentInput', { read: ElementRef, static: false })
@ViewChild('serverContentInput', { static: false })
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...