Consider this Angular component template:
<input #userInput type="text" value="Hello">
<button (click)="onClick(userInput.value)">Show</button>
<p>{{message}}</p>And this component class:
message = '';
onClick(value: string) {
this.message = value;
}What will be displayed in the paragraph after clicking the button?
<input #userInput type="text" value="Hello"> <button (click)="onClick(userInput.value)">Show</button> <p>{{message}}</p>
Think about what #userInput refers to and what userInput.value accesses.
The template reference variable #userInput points to the input element. Accessing userInput.value gets the current value of the input, which is 'Hello'. Clicking the button calls onClick with this value, updating message to 'Hello'.
Choose the correct syntax to declare a template reference variable named myInput on an <input> element.
Template reference variables use a specific prefix symbol.
The correct syntax uses the hash symbol # before the variable name, like #myInput. The other prefixes are incorrect in Angular templates.
Given this template snippet:
<input #inputRef type="text"> <button (click)="logValue()">Log</button>
And this component code:
logValue() {
console.log(inputRef.value);
}Why does this cause a runtime error?
<input #inputRef type="text"> <button (click)="logValue()">Log</button>
Consider where inputRef is accessible in Angular.
Template reference variables exist only in the template scope. They are not accessible directly in the component class methods unless passed as parameters. Trying to access inputRef inside logValue() causes a ReferenceError.
Consider this Angular component template:
<button #btn (click)="increment(btn.textContent)">Click me</button>
<p>Count: {{count}}</p>And this component class:
count = 0;
increment(text: string) {
if (text === 'Click me') {
this.count += 1;
}
}What is the value of count after clicking the button twice?
<button #btn (click)="increment(btn.textContent)">Click me</button>
<p>Count: {{count}}</p>Check what btn.textContent returns and how increment updates count.
The template reference variable #btn points to the button element. Its textContent is 'Click me'. Each click calls increment with 'Click me', which increases count by 1. After two clicks, count is 2.
Choose the correct statement about template reference variables in Angular.
Think about what template reference variables can point to and their scope.
Template reference variables can point to any DOM element or Angular component/directive instance in the template. They exist only in the template scope and are not accessible directly in the component class unless passed. They are not limited to <ng-template> and do not automatically update class properties.