Angular: Local References in templates.

I love learning about technology and sharing that with others
Introduction
So here we will learn about the local references in templates work, so what does this mean, this means that we can pass the complete HTML element to the Typescript file and then use it there. here we have attached a reference to the element and then used it to fetch the value
template
- we have to name it using hash.
- here the local reference is servernameInput and we pass that in the method call and then fetch the value and then send that value using event Emitter to the parent.
<div class="row">
<div class="col-xs-12">
<p>Add new Servers or blueprints!</p>
<label>Server Name</label>
<!-- <input type="text" class="form-control" [(ngModel)]="newServerName"> -->
<input type="text" class="form-control" #servernameInput>
<label>Server Content</label>
<input type="text" class="form-control" [(ngModel)]="newServerContent">
<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>
Typrescript file for the above template
- here we can see that the servernameInput element is the type HTMLInputElement and then we use the method value to get the values from that.
import { Component, OnInit,EventEmitter, Output } from '@angular/core';
@Component({
selector: 'app-cockpit',
templateUrl: './cockpit.component.html',
styleUrls: ['./cockpit.component.css']
})
export class CockpitComponent implements OnInit {
newServerContent = '';
@Output() serverCreated = new EventEmitter<{serverName:string,serverContent:string}>();;
@Output() blueprintCreated = new EventEmitter<{serverName:string,serverContent:string}>();
constructor() { }
ngOnInit(): void {
}
onAddServer(servernameInput : HTMLInputElement) {
this.serverCreated.emit({
serverName:servernameInput.value,
serverContent:this.newServerContent
})
}
onAddBlueprint(servernameInput:HTMLInputElement) {
this.blueprintCreated.emit({
serverName:servernameInput.value,
serverContent:this.newServerContent
})
}
}

