Currently, I am working on a project using Angular-7
. I have been trying to access elements directly from the TypeScript file by utilizing @ViewChild
, but encountered an error message. The code snippet in question is:
@ViewChild('serverContentInput', { read: true, static: true }) serverContentInput: ElementRef;
and it seems that it is not able to Access the Template & DOM with @ViewChild
Error:
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>