Template variables

Template variables help you use data from one part of a template in another part of the template. With template variables, you can perform tasks such as respond to user input or finely tune your application's forms.

A template variable can refer to the following:

  • a DOM element within a template
  • a directive
  • TemplateRef
  • a web component
See the live example for a working example containing the code snippets in this guide.

In the template, you use the hash symbol, # , to declare a template variable. The following template variable, #phone , declares a phone variable on an <input> element.

You can refer to a template variable anywhere in the component's template. Here, a <button> further down the template refers to the phone variable.

How Angular assigns values to template variables

Angular assigns a template variable a value based on where you declare the variable:

  • If you declare the variable on a component, the variable refers to the component instance.
  • If you declare the variable on a standard HTML tag, the variable refers to the element.
  • If you declare the variable on an <ng-template> element, the variable refers to a TemplateRef instance, which represents the template. For more information on <ng-template> , see How Angular uses the asterisk, * , syntax in Structural directives .
  • If the variable specifies a name on the right-hand side, such as #var=" ngModel " , the variable refers to the directive or component on the element with a matching exportAs name.

Using NgForm with template variables

In most cases, Angular sets the template variable's value to the element on which it occurs. In the previous example, phone refers to the phone number <input> . The button's click handler passes the <input> value to the component's callPhone() method.

The NgForm directive demonstrates getting a reference to a different value by reference a directive's exportAs name. In the following example, the template variable, itemForm , appears three times separated by HTML.

Without the ngForm attribute value, the reference value of itemForm would be the HTMLFormElement , <form> . There is, however, a difference between a Component and a Directive in that Angular references a Component without specifying the attribute value, and a Directive does not change the implicit reference, or the element.

With NgForm , itemForm is a reference to the NgForm directive with the ability to track the value and validity of every control in the form.

Unlike the native <form> element, the NgForm directive has a form property. The NgForm form property allows you to disable the submit button if the itemForm.form.valid is invalid.

Template variable scope

You can refer to a template variable anywhere within its surrounding template. Structural directives , such as * ngIf and * ngFor , or <ng-template> act as a template boundary. You cannot access template variables outside of these boundaries.

Define a variable only once in the template so the runtime value remains predictable.

Accessing in a nested template

An inner template can access template variables that the outer template defines.

In the following example, changing the text in the <input> changes the value in the <span> because Angular immediately updates changes through the template variable, ref1 .

In this case, there is an implied <ng-template> around the <span> and the definition of the variable is outside of it. Accessing a template variable from the parent template works because the child template inherits the context from the parent template.

Rewriting the above code in a more verbose form explicitly shows the <ng-template> .

However, accessing a template variable from outside the parent template doesn't work.

The verbose form shows that ref2 is outside the parent template.

Consider the following example that uses * ngFor .

Here, ref.value doesn't work. The structural directive, * ngFor instantiates the template twice because * ngFor iterates over the two items in the array. It is impossible to define what the ref.value reference signifies.

With structural directives, such as * ngFor or * ngIf , there is no way for Angular to know if a template is ever instantiated.

As a result, Angular isn't able to access the value and returns an error.

Accessing a template variable within <ng-template>

When you declare the variable on an <ng-template> , the variable refers to a TemplateRef instance, which represents the template.

In this example, clicking the button calls the log() function, which outputs the value of #ref3 to the console. Because the #ref variable is on an <ng-template> , the value is TemplateRef .

The following is the expanded browser console output of the TemplateRef () function with the name of TemplateRef .

Template input variable

A template input variable is a variable you can reference within a single instance of the template. You declare a template input variable using the let keyword as in let hero .

There are several such variables in this example: hero , i , and odd .

The variable's scope is limited to a single instance of the repeated template. You can use the same variable name again in the definition of other structural directives.

In contrast, you declare a template variable by prefixing the variable name with # , as in #var . A template variable refers to its attached element, component, or directive.

Template input variables and template variables names have their own namespaces. The template input variable hero in let hero is distinct from the template variable hero in #hero .

© 2010–2021 Google, Inc. Licensed under the Creative Commons Attribution License 4.0. https://v11.angular.io/guide/template-reference-variables

Briebug Blog

Briebug Blog

Sharing our thoughts with the community

angular html variable assignment

Template Variables in Angular

01/28/2021 12:00 AM

Angular provides a very rich development platform for modern web applications. That richness extends into the template as much as it does into the JavaScript code areas. A very useful but potentially obscure feature of Angular templates are the Template Variable ; sometimes  also referred to as Template Reference Variables or Local References .

What is a Template Variable?

A template variable is a variable that is created in, and identifies a component or element within, the template itself. In other words, a local reference to some element in your template that you wish to refer to, pass around, pass back to or reference from the TypeScript component or call things on.

Template variables may refer to any one of the following in a template:

  • DOM elements
  • TemplateRefs
  • Web Components

Defining a Template Variable

Creating a template variable is very easy with Angular. Simply add a unique identifier to whatever it is you wish to reference, like so:

The reference in the example here is defined by the #email attribute added to the element. The name of the reference is simply email so, when actually referencing the variable, drop the hash # .

That's all you need to define a template variable. You may in fact already be defining them in some of your templates. For example, if you use template forms, when you bind the form to ngForm you are in fact defining a template variable for the form:

The form above is referenced by the identifier form and that reference may be used in the template or passed to methods on the component.

Elements are easy to define a template variable reference for. Directives are a little less obvious; but you have already seen how. The input example is defining a reference on an element. The form example, however, is actually defining a reference the ngForm directive. To define a template variable for a directive, simply assign the variable to the directive.

Template Variable Scope

Template variables are available within the template they are defined in. Note that if you use any structural directive, or use <ng-template> or <ng-container> , those directives and elements create a child scope. Template variables defined on or in such child scopes are only accessible within those scopes.

Using a Template Variable

To use a template variable, use the identifier name. In the case of the example form above; if we were to submit that form we would pass the form to our submit method like so:

This is template local access to a template variable. In this case, the reference is passed into the component via a method.

The code in the component would access the FormGroup on the ngForm directive that is passed to the submit() method. The example below destructures the NgForm.form property from the passed form directive to get ahold of the actual form group:

Template variables may be used strictly within the template as well. Consider the input example and the need to display validation errors in a template form:

View Children

Another way to reference template variables is through the ViewChild decorator. Within a component, properties so decorated may access one of a number of types of view children identified in one of many ways. Elements, directives and child components may all be referenced directly via template variables within the component.

To access a specific child component of a particular type, define a variable for it in the template:

And use @ViewChild('child') in the component:

Note that many children will be static in that they do not change throughout the lifetime of the component. In some cases, you may need to update the component reference to a view child. In that case you should set static to false which will ensure the reference is updated in the event that the content changes. This should not generally be required for template references but there are edge cases.

Element References

When using @ViewChild to access something from your template in the component, you may also read alternative forms or related references. For example, to get a reference to the HTML element instead of the component:

You could also reference any provider provided on your child component as well:

Template References

Template references are one of the more powerful tools in the Angular toolbox. They can be used with <ng-template> to define child templates that may be referenced elsewhere in the component's template, passed to child components or referenced in the component code.

A simple use case for template references, with template variables, is to allow cleaner markup in your templates while allowing alternative representations in certain areas of the template:

With the following component for support:

Alternative Representations

Another excellent use case for templates and template references is to contain alternative representations or content to be displayed under certain circumstances. A common example is when loading data and displaying a message while the data is loading:

You can also nest such container/template structures as well. Another common pattern is to display a different message when after loading is complete and you still have no data (i.e. no items were found):

Simple yet Powerful

Template variables are a very simple tool in Angular templates, however, they also provide access to some of its most advanced and powerful features. They bring a level of template purity and simplicity, allowing the developer to avoid creating unnecessary properties and methods in their component. Instead, directly accessing the relevant functionality or data strictly from the template.

When combined with @ViewChild and TemplateRef , they bring a significant amount of power to the table. They can allow cleaner template design and better template organization where interchangeable content can be encapsulated. Further, templates can be driven in a more dynamic manner with template references.

This website requires JavaScript.

Este sitio web requiere JavaScript.

Get 73% off the Angular Master bundle

See the bundle then add to cart and your discount is applied.

Write Angular like a pro.

Follow the ultimate Angular roadmap.

Ultimate Courses

Angular Template Reference Variables In-Depth

Todd Motto

by Todd Motto

Feb 23, 2022

2 mins read

Learn Angular the right way.

The most complete guide to learning Angular ever built. Trusted by 82,951 students .

Todd Motto

with Todd Motto

In this post you’ll learn how to use Template Reference Variables, often known as “Template Refs”, in Angular.

In Angular, components have a template property, that holds elements and other components. A template reference variable is a feature that allows us to gain access to a part of our template.

This could be an element, component, or could be a directive. Template reference variables are cleverly implemented and can be used in various ways.

The first might be to simply export a reference to an element. Here we can attach a # to an <input> and provide a variable name (hence the template reference ‘variable’):

You can think of this syntax as an “export”. We are exporting a reference to the element.

That means that we can now access properties on that reference variable as if it was returned to us through plain JavaScript (think what you’d get back using document.querySelector('input') and that’s what we have here):

This would log out an empty string for coffee.value as we have no value . Our coffee variable is directly giving us an HTMLInputElement .

Angular Directives In-Depth eBook Cover

Directives, simple right? Wrong! On the outside they look simple, but even skilled Angular devs haven’t grasped every concept in this eBook.

That went smoothly, check your email.

For us to see the value as we type, we would need to introduce the ngModel Directive:

Give it a try and type something into the <input> :

So here’s the next great feature of template refs.

Let’s export a reference to our ngModel and change the context of what #coffee returns us.

By specifying #coffee we are implicitly letting Angular decide what to export, because we are not specifying anything other than binding to the element.

We’re binding ngModel , which is now ‘part of’ our <input> . Let’s export it:

By passing #coffee="ngModel" we are explicitly binding a reference to our tracked ngModel directive.

No longer do we have an HTMLInputElement . We have a reference to NgControl .

You can check the source code for NgControl here, which extends the NgControl and AbstractControlDirective classes.

Why are we looking at this? Because it shows you every property available to you, which is exactly why we’ve referenced not only value but pristine and touched as well.

Try them out below, our template reference variable is mirroring the ngModel :

We can further this and access a template ref inside a component , so we can access properties and methods from inside the class and not just the template .

This is achieved through using perhaps TemplateRef or ElementRef alongside a @ViewChild decorator. Read the above article on how to do it and more deep working, but essentially it looks like this:

That’s a nice introduction to template refs, and I hope it gives you some deeper understanding as to how to use them, when and where. Not only this, but what to expect back when you declare a template ref and how to also export references to things like directives.

If you are serious about your Angular skills, your next step is to take a look at my Angular courses where you’ll learn Angular, TypeScript, RxJS and state management principles from beginning to expert level.

Happy reffing!

Related blogs 🚀

Angular's @if and @else control flow explained.

Angular templates just got the best upgrade in years: control flow blocks.

Todd Motto

Dec 4, 2023

Binding Angular Route Params to Component @Input

ActivatedRoute just left the chat. Say hello to router input bindings straight to your components.

Nov 23, 2023

Angulars NgIf, Else, Then - Explained

Angular’s NgIf directive doesn’t need to be complicated, yet you’re here because it kind of is. So let’s take it back to basics and uncover NgIf, E...

Oct 18, 2023

Using ngStyle in Angular for dynamic styling

In this tutorial you’ll learn how to dynamically apply CSS styles in Angular via ngStyle, but we’ll also cover the style property binding for full ...

Mar 13, 2023

Passing data into Angular components with @Input

Angular components are the building blocks of applications, and component communication via one-way data flow is the key to writing clean Angular a...

Mar 11, 2023

Get the Current Route or URL with the Angular Router

In this post you’ll learn how to get the current route, or URL, with the Angular router.

Mar 4, 2023

Free eBooks:

Angular Directives In-Depth eBook Cover

You've got mail! Enjoy.

JavaScript Array Methods eBook Cover

Cookies are used to analyze traffic and optimize experience.

A newer version of this site just became available. Please refresh this page to activate it.

Template Syntax

Learn how to write templates that display data and consume user events with the help of data binding.

The Angular application manages what the user sees and can do, achieving this through the interaction of a component class instance (the component ) and its user-facing template.

You may be familiar with the component/template duality from your experience with model-view-controller (MVC) or model-view-viewmodel (MVVM). In Angular, the component plays the part of the controller/viewmodel, and the template represents the view.

This guide covers the basic elements of the Angular template syntax, elements you'll need to construct the view:

HTML in templates

Interpolation ( {{...}} ), template expressions, template statements.

  • Binding syntax

Property binding ( [property] )

Attribute, class, and style bindings, event binding ( (event) ).

  • Two-way data binding ( [(...)] )

Built-in directives

  • NgModel ( [(ngModel)] )

Template input variables

  • Microsyntax

The NgSwitch directives

Template reference variables ( #var ), input and output properties ( @input and @output ).

  • safe navigation operator ( ?. )

HTML is the language of the Angular template. Almost all HTML syntax is valid template syntax. The <script> element is a notable exception; it is forbidden, eliminating the risk of script injection attacks. In practice, <script> is ignored and a warning appears in the browser console. See the Security page for details.

Some legal HTML doesn't make much sense in a template. The <html> , <body> , and <base> elements have no useful role. Pretty much everything else is fair game.

You can extend the HTML vocabulary of your templates with components and directives that appear as new elements and attributes. In the following sections, you'll learn how to get and set DOM (Document Object Model) values dynamically through data binding.

Begin with the first form of data binding—interpolation—to see how much richer template HTML can be.

You met the double-curly braces of interpolation, {{ and }} , early in your Angular education.

You use interpolation to weave calculated strings into the text between HTML element tags and within attribute assignments.

The text between the braces is often the name of a component property. Angular replaces that name with the string value of the corresponding component property. In the example above, Angular evaluates the title and heroImageUrl properties and "fills in the blanks", first displaying a bold application title and then a heroic image.

More generally, the text between the braces is a template expression that Angular first evaluates and then converts to a string . The following interpolation illustrates the point by adding the two numbers:

The expression can invoke methods of the host component such as getVal() , seen here:

Angular evaluates all expressions in double curly braces, converts the expression results to strings, and links them with neighboring literal strings. Finally, it assigns this composite interpolated result to an element or directive property .

You appear to be inserting the result between element tags and assigning it to attributes. It's convenient to think so, and you rarely suffer for this mistake. Though this is not exactly true. Interpolation is a special syntax that Angular converts into a property binding , as is explained below .

But first, let's take a closer look at template expressions and statements.

A template expression produces a value. Angular executes the expression and assigns it to a property of a binding target; the target might be an HTML element, a component, or a directive.

The interpolation braces in {{1 + 1}} surround the template expression 1 + 1 . In the property binding section below, a template expression appears in quotes to the right of the  = symbol as in [property]="expression" .

You write these template expressions in a language that looks like JavaScript. Many JavaScript expressions are legal template expressions, but not all.

JavaScript expressions that have or promote side effects are prohibited, including:

  • assignments ( = , += , -= , ...)
  • chaining expressions with ; or ,
  • increment and decrement operators ( ++ and -- )

Other notable differences from JavaScript syntax include:

  • no support for the bitwise operators | and &
  • new template expression operators , such as | and ?.

Expression context

The expression context is typically the component instance. In the following snippets, the title within double-curly braces and the isUnchanged in quotes refer to properties of the AppComponent .

An expression may also refer to properties of the template's context such as a template input variable ( let hero ) or a template reference variable ( #heroInput ).

The context for terms in an expression is a blend of the template variables , the directive's context object (if it has one), and the component's members . If you reference a name that belongs to more than one of these namespaces, the template variable name takes precedence, followed by a name in the directive's context , and, lastly, the component's member names.

The previous example presents such a name collision. The component has a hero property and the *ngFor defines a hero template variable. The hero in {{hero.name}} refers to the template input variable, not the component's property.

Template expressions cannot refer to anything in the global namespace. They can't refer to window or document . They can't call console.log or Math.max . They are restricted to referencing members of the expression context.

Expression guidelines

Template expressions can make or break an application. Please follow these guidelines:

No visible side effects

Quick execution, idempotence.

The only exceptions to these guidelines should be in specific circumstances that you thoroughly understand.

A template expression should not change any application state other than the value of the target property.

This rule is essential to Angular's "unidirectional data flow" policy. You should never worry that reading a component value might change some other displayed value. The view should be stable throughout a single rendering pass.

Angular executes template expressions after every change detection cycle. Change detection cycles are triggered by many asynchronous activities such as promise resolutions, http results, timer events, keypresses and mouse moves.

Expressions should finish quickly or the user experience may drag, especially on slower devices. Consider caching values when their computation is expensive.

Although it's possible to write quite complex template expressions, you should avoid them.

A property name or method call should be the norm. An occasional Boolean negation ( ! ) is OK. Otherwise, confine application and business logic to the component itself, where it will be easier to develop and test.

An idempotent expression is ideal because it is free of side effects and improves Angular's change detection performance.

In Angular terms, an idempotent expression always returns exactly the same thing until one of its dependent values changes.

Dependent values should not change during a single turn of the event loop. If an idempotent expression returns a string or a number, it returns the same string or number when called twice in a row. If the expression returns an object (including an Array ), it returns the same object reference when called twice in a row.

A template statement responds to an event raised by a binding target such as an element, component, or directive. You'll see template statements in the event binding section, appearing in quotes to the right of the =  symbol as in (event)="statement" .

A template statement has a side effect . That's the whole point of an event. It's how you update application state from user action.

Responding to events is the other side of Angular's "unidirectional data flow". You're free to change anything, anywhere, during this turn of the event loop.

Like template expressions, template statements use a language that looks like JavaScript. The template statement parser differs from the template expression parser and specifically supports both basic assignment ( = ) and chaining expressions (with ; or , ).

However, certain JavaScript syntax is not allowed:

  • increment and decrement operators, ++ and --
  • operator assignment, such as += and -=
  • the bitwise operators | and &
  • the template expression operators

Statement context

As with expressions, statements can refer only to what's in the statement context such as an event handling method of the component instance.

The statement context is typically the component instance. The deleteHero in (click)="deleteHero()" is a method of the data-bound component.

The statement context may also refer to properties of the template's own context. In the following examples, the template $event object, a template input variable ( let hero ), and a template reference variable ( #heroForm ) are passed to an event handling method of the component.

Template context names take precedence over component context names. In deleteHero(hero) above, the hero is the template input variable, not the component's hero property.

Template statements cannot refer to anything in the global namespace. They can't refer to window or document . They can't call console.log or Math.max .

Statement guidelines

As with expressions, avoid writing complex template statements. A method call or simple property assignment should be the norm.

Now that you have a feel for template expressions and statements, you're ready to learn about the varieties of data binding syntax beyond interpolation.

Binding syntax: An overview

Data binding is a mechanism for coordinating what users see, with application data values. While you could push values to and pull values from HTML, the application is easier to write, read, and maintain if you turn these chores over to a binding framework. You simply declare bindings between binding sources and target HTML elements and let the framework do the work.

Angular provides many kinds of data binding. This guide covers most of them, after a high-level view of Angular data binding and its syntax.

Binding types can be grouped into three categories distinguished by the direction of data flow: from the source-to-view , from view-to-source , and in the two-way sequence: view-to-source-to-view :

Binding types other than interpolation have a target name to the left of the equal sign, either surrounded by punctuation ( [] , () ) or preceded by a prefix ( bind- , on- , bindon- ).

The target name is the name of a property . It may look like the name of an attribute but it never is. To appreciate the difference, you must develop a new way to think about template HTML.

A new mental model

With all the power of data binding and the ability to extend the HTML vocabulary with custom markup, it is tempting to think of template HTML as HTML Plus .

It really is HTML Plus. But it's also significantly different than the HTML you're used to. It requires a new mental model.

In the normal course of HTML development, you create a visual structure with HTML elements, and you modify those elements by setting element attributes with string constants.

You still create a structure and initialize attribute values this way in Angular templates.

Then you learn to create new elements with components that encapsulate HTML and drop them into templates as if they were native HTML elements.

That's HTML Plus.

Then you learn about data binding. The first binding you meet might look like this:

You'll get to that peculiar bracket notation in a moment. Looking beyond it, your intuition suggests that you're binding to the button's disabled attribute and setting it to the current value of the component's isUnchanged property.

Your intuition is incorrect! Your everyday HTML mental model is misleading. In fact, once you start data binding, you are no longer working with HTML attributes . You aren't setting attributes. You are setting the properties of DOM elements, components, and directives.

HTML attribute vs. DOM property

The distinction between an HTML attribute and a DOM property is crucial to understanding how Angular binding works.

Attributes are defined by HTML. Properties are defined by the DOM (Document Object Model).

A few HTML attributes have 1:1 mapping to properties. id is one example.

Some HTML attributes don't have corresponding properties. colspan is one example.

Some DOM properties don't have corresponding attributes. textContent is one example.

Many HTML attributes appear to map to properties ... but not in the way you might think!

That last category is confusing until you grasp this general rule:

Attributes initialize DOM properties and then they are done. Property values can change; attribute values can't.

For example, when the browser renders <input type="text" value="Bob"> , it creates a corresponding DOM node with a value property initialized to "Bob".

When the user enters "Sally" into the input box, the DOM element value property becomes "Sally". But the HTML value attribute remains unchanged as you discover if you ask the input element about that attribute: input.getAttribute('value') returns "Bob".

The HTML attribute value specifies the initial value; the DOM value property is the current value.

The disabled attribute is another peculiar example. A button's disabled property is false by default so the button is enabled. When you add the disabled attribute , its presence alone initializes the button's disabled property to true so the button is disabled.

Adding and removing the disabled attribute disables and enables the button. The value of the attribute is irrelevant, which is why you cannot enable a button by writing <button disabled="false">Still Disabled</button> .

Setting the button's disabled property (say, with an Angular binding) disables or enables the button. The value of the property matters.

The HTML attribute and the DOM property are not the same thing, even when they have the same name.

This fact bears repeating: Template binding works with properties and events , not attributes .

In the world of Angular, the only role of attributes is to initialize element and directive state. When you write a data binding, you're dealing exclusively with properties and events of the target object. HTML attributes effectively disappear.

With this model firmly in mind, read on to learn about binding targets.

Binding targets

The target of a data binding is something in the DOM. Depending on the binding type, the target can be an (element | component | directive) property, an (element | component | directive) event, or (rarely) an attribute name. The following table summarizes:

With this broad view in mind, you're ready to look at binding types in detail.

Write a template property binding to set a property of a view element. The binding sets the property to the value of a template expression .

The most common property binding sets an element property to a component property value. An example is binding the src property of an image element to a component's heroImageUrl property:

Another example is disabling a button when the component says that it isUnchanged :

Another is setting a property of a directive:

Yet another is setting the model property of a custom component (a great way for parent and child components to communicate):

People often describe property binding as one-way data binding because it flows a value in one direction, from a component's data property into a target element property.

You cannot use property binding to pull values out of the target element. You can't bind to a property of the target element to read it. You can only set it.

Similarly, you cannot use property binding to call a method on the target element.

If the element raises events, you can listen to them with an event binding .

If you must read a target element property or call one of its methods, you'll need a different technique. See the API reference for ViewChild and ContentChild .

Binding target

An element property between enclosing square brackets identifies the target property. The target property in the following code is the image element's src property.

Some people prefer the bind- prefix alternative, known as the canonical form :

The target name is always the name of a property, even when it appears to be the name of something else. You see src and may think it's the name of an attribute. No. It's the name of an image element property.

Element properties may be the more common targets, but Angular looks first to see if the name is a property of a known directive, as it is in the following example:

Technically, Angular is matching the name to a directive input , one of the property names listed in the directive's inputs array or a property decorated with @Input() . Such inputs map to the directive's own properties.

If the name fails to match a property of a known directive or element, Angular reports an “unknown directive” error.

Avoid side effects

As mentioned previously, evaluation of a template expression should have no visible side effects. The expression language itself does its part to keep you safe. You can't assign a value to anything in a property binding expression nor use the increment and decrement operators.

Of course, the expression might invoke a property or method that has side effects. Angular has no way of knowing that or stopping you.

The expression could call something like getFoo() . Only you know what getFoo() does. If getFoo() changes something and you happen to be binding to that something, you risk an unpleasant experience. Angular may or may not display the changed value. Angular may detect the change and throw a warning error. In general, stick to data properties and to methods that return values and do no more.

Return the proper type

The template expression should evaluate to the type of value expected by the target property. Return a string if the target property expects a string. Return a number if the target property expects a number. Return an object if the target property expects an object.

The hero property of the HeroDetail component expects a Hero object, which is exactly what you're sending in the property binding:

Remember the brackets

The brackets tell Angular to evaluate the template expression. If you omit the brackets, Angular treats the string as a constant and initializes the target property with that string. It does not evaluate the string!

Don't make the following mistake:

One-time string initialization

You should omit the brackets when all of the following are true:

  • The target property accepts a string value.
  • The string is a fixed value that you can bake into the template.
  • This initial value never changes.

You routinely initialize attributes this way in standard HTML, and it works just as well for directive and component property initialization. The following example initializes the prefix property of the HeroDetailComponent to a fixed string, not a template expression. Angular sets it and forgets about it.

The [hero] binding, on the other hand, remains a live binding to the component's currentHero property.

Property binding or interpolation?

You often have a choice between interpolation and property binding. The following binding pairs do the same thing:

Interpolation is a convenient alternative to property binding in many cases.

When rendering data values as strings, there is no technical reason to prefer one form to the other. You lean toward readability, which tends to favor interpolation. You suggest establishing coding style rules and choosing the form that both conforms to the rules and feels most natural for the task at hand.

When setting an element property to a non-string data value, you must use property binding .

Content security

Imagine the following malicious content .

Fortunately, Angular data binding is on alert for dangerous HTML. It sanitizes the values before displaying them. It will not allow HTML with script tags to leak into the browser, neither with interpolation nor property binding.

Interpolation handles the script tags differently than property binding but both approaches render the content harmlessly.

evil title made safe

back to top

The template syntax provides specialized one-way bindings for scenarios less well suited to property binding.

Attribute binding

You can set the value of an attribute directly with an attribute binding .

This is the only exception to the rule that a binding sets a target property. This is the only binding that creates and sets an attribute.

This guide stresses repeatedly that setting an element property with a property binding is always preferred to setting the attribute with a string. Why does Angular offer attribute binding?

You must use attribute binding when there is no element property to bind.

Consider the ARIA , SVG , and table span attributes. They are pure attributes. They do not correspond to element properties, and they do not set element properties. There are no property targets to bind to.

This fact becomes painfully obvious when you write something like this.

And you get this error:

As the message says, the <td> element does not have a colspan property. It has the "colspan" attribute , but interpolation and property binding can set only properties , not attributes.

You need attribute bindings to create and bind to such attributes.

Attribute binding syntax resembles property binding. Instead of an element property between brackets, start with the prefix attr , followed by a dot ( . ) and the name of the attribute. You then set the attribute value, using an expression that resolves to a string.

Bind [attr.colspan] to a calculated value:

Here's how the table renders:

One of the primary use cases for attribute binding is to set ARIA attributes, as in this example:

Class binding

You can add and remove CSS class names from an element's class attribute with a class binding .

Class binding syntax resembles property binding. Instead of an element property between brackets, start with the prefix class , optionally followed by a dot ( . ) and the name of a CSS class: [class.class-name] .

The following examples show how to add and remove the application's "special" class with class bindings. Here's how to set the attribute without binding:

You can replace that with a binding to a string of the desired class names; this is an all-or-nothing, replacement binding.

Finally, you can bind to a specific class name. Angular adds the class when the template expression evaluates to truthy. It removes the class when the expression is falsy.

While this is a fine way to toggle a single class name, the NgClass directive is usually preferred when managing multiple class names at the same time.

Style binding

You can set inline styles with a style binding .

Style binding syntax resembles property binding. Instead of an element property between brackets, start with the prefix style , followed by a dot ( . ) and the name of a CSS style property: [style.style-property] .

Some style binding styles have a unit extension. The following example conditionally sets the font size in “em” and “%” units .

While this is a fine way to set a single style, the NgStyle directive is generally preferred when setting several inline styles at the same time.

Note that a style property name can be written in either dash-case , as shown above, or camelCase , such as fontSize .

The bindings directives you've met so far flow data in one direction: from a component to an element .

Users don't just stare at the screen. They enter text into input boxes. They pick items from lists. They click buttons. Such user actions may result in a flow of data in the opposite direction: from an element to a component .

The only way to know about a user action is to listen for certain events such as keystrokes, mouse movements, clicks, and touches. You declare your interest in user actions through Angular event binding.

Event binding syntax consists of a target event name within parentheses on the left of an equal sign, and a quoted template statement on the right. The following event binding listens for the button's click events, calling the component's onSave() method whenever a click occurs:

Target event

A name between parentheses — for example, (click) — identifies the target event. In the following example, the target is the button's click event.

Some people prefer the on- prefix alternative, known as the canonical form :

Element events may be the more common targets, but Angular looks first to see if the name matches an event property of a known directive, as it does in the following example:

The myClick directive is further described in the section on aliasing input/output properties .

If the name fails to match an element event or an output property of a known directive, Angular reports an “unknown directive” error.

$event and event handling statements

In an event binding, Angular sets up an event handler for the target event.

When the event is raised, the handler executes the template statement. The template statement typically involves a receiver, which performs an action in response to the event, such as storing a value from the HTML control into a model.

The binding conveys information about the event, including data values, through an event object named $event .

The shape of the event object is determined by the target event. If the target event is a native DOM element event, then $event is a DOM event object , with properties such as target and target.value .

Consider this example:

This code sets the input box value property by binding to the name property. To listen for changes to the value, the code binds to the input box's input event. When the user makes changes, the input event is raised, and the binding executes the statement within a context that includes the DOM event object, $event .

To update the name property, the changed text is retrieved by following the path $event.target.value .

If the event belongs to a directive (recall that components are directives), $event has whatever shape the directive decides to produce.

Custom events with EventEmitter

Directives typically raise custom events with an Angular EventEmitter . The directive creates an EventEmitter and exposes it as a property. The directive calls EventEmitter.emit(payload) to fire an event, passing in a message payload, which can be anything. Parent directives listen for the event by binding to this property and accessing the payload through the $event object.

Consider a HeroDetailComponent that presents hero information and responds to user actions. Although the HeroDetailComponent has a delete button it doesn't know how to delete the hero itself. The best it can do is raise an event reporting the user's delete request.

Here are the pertinent excerpts from that HeroDetailComponent :

src/app/hero-detail.component.ts (template)

Src/app/hero-detail.component.ts (deleterequest).

The component defines a deleteRequest property that returns an EventEmitter . When the user clicks delete , the component invokes the delete() method, telling the EventEmitter to emit a Hero object.

Now imagine a hosting parent component that binds to the HeroDetailComponent 's deleteRequest event.

When the deleteRequest event fires, Angular calls the parent component's deleteHero method, passing the hero-to-delete (emitted by HeroDetail ) in the $event variable.

Template statements have side effects

The deleteHero method has a side effect: it deletes a hero. Template statement side effects are not just OK, but expected.

Deleting the hero updates the model, perhaps triggering other changes including queries and saves to a remote server. These changes percolate through the system and are ultimately displayed in this and other views.

Two-way binding ( [(...)] )

You often want to both display a data property and update that property when the user makes changes.

On the element side that takes a combination of setting a specific element property and listening for an element change event.

Angular offers a special two-way data binding syntax for this purpose, [(x)] . The [(x)] syntax combines the brackets of property binding , [x] , with the parentheses of event binding , (x) .

Visualize a banana in a box to remember that the parentheses go inside the brackets.

The [(x)] syntax is easy to demonstrate when the element has a settable property called x and a corresponding event named xChange . Here's a SizerComponent that fits the pattern. It has a size value property and a companion sizeChange event:

src/app/sizer.component.ts

The initial size is an input value from a property binding. Clicking the buttons increases or decreases the size , within min/max values constraints, and then raises ( emits ) the sizeChange event with the adjusted size.

Here's an example in which the AppComponent.fontSizePx is two-way bound to the SizerComponent :

The AppComponent.fontSizePx establishes the initial SizerComponent.size value. Clicking the buttons updates the AppComponent.fontSizePx via the two-way binding. The revised AppComponent.fontSizePx value flows through to the style binding, making the displayed text bigger or smaller.

The two-way binding syntax is really just syntactic sugar for a property binding and an event binding. Angular desugars the SizerComponent binding into this:

The $event variable contains the payload of the SizerComponent.sizeChange event. Angular assigns the $event value to the AppComponent.fontSizePx when the user clicks the buttons.

Clearly the two-way binding syntax is a great convenience compared to separate property and event bindings.

It would be convenient to use two-way binding with HTML form elements like <input> and <select> . However, no native HTML element follows the x value and xChange event pattern.

Fortunately, the Angular NgModel directive is a bridge that enables two-way binding to form elements.

Earlier versions of Angular included over seventy built-in directives. The community contributed many more, and countless private directives have been created for internal applications.

You don't need many of those directives in Angular. You can often achieve the same results with the more capable and expressive Angular binding system. Why create a directive to handle a click when you can write a simple binding such as this?

You still benefit from directives that simplify complex tasks. Angular still ships with built-in directives; just not as many. You'll write your own directives, just not as many.

This segment reviews some of the most frequently used built-in directives, classified as either attribute directives or structural directives .

Built-in attribute directives

Attribute directives listen to and modify the behavior of other HTML elements, attributes, properties, and components. They are usually applied to elements as if they were HTML attributes, hence the name.

Many details are covered in the Attribute Directives guide. Many Angular modules such as the RouterModule and the FormsModule define their own attribute directives. This section is an introduction to the most commonly used attribute directives:

  • NgClass - add and remove a set of CSS classes
  • NgStyle - add and remove a set of HTML styles
  • NgModel - two-way data binding to an HTML form element

You typically control how elements appear by adding and removing CSS classes dynamically. You can bind to the ngClass to add or remove several classes simultaneously.

A class binding is a good way to add or remove a single class.

To add or remove many CSS classes at the same time, the NgClass directive may be the better choice.

Try binding ngClass to a key:value control object. Each key of the object is a CSS class name; its value is true if the class should be added, false if it should be removed.

Consider a setCurrentClasses component method that sets a component property, currentClasses with an object that adds or removes three classes based on the true / false state of three other component properties:

Adding an ngClass property binding to currentClasses sets the element's classes accordingly:

It's up to you to call setCurrentClassess() , both initially and when the dependent properties change.

You can set inline styles dynamically, based on the state of the component. With NgStyle you can set many inline styles simultaneously.

A style binding is an easy way to set a single style value.

To set many inline styles at the same time, the NgStyle directive may be the better choice.

Try binding ngStyle to a key:value control object. Each key of the object is a style name; its value is whatever is appropriate for that style.

Consider a setCurrentStyles component method that sets a component property, currentStyles with an object that defines three styles, based on the state of three other component propertes:

Adding an ngStyle property binding to currentStyles sets the element's styles accordingly:

It's up to you to call setCurrentStyles() , both initially and when the dependent properties change.

NgModel - Two-way binding to form elements with [(ngModel)]

When developing data entry forms, you often both display a data property and update that property when the user makes changes.

Two-way data binding with the NgModel directive makes that easy. Here's an example:

FormsModule is required to use ngModel

Before using the ngModel directive in a two-way data binding, you must import the FormsModule and add it to the Angular module's imports list. Learn more about the FormsModule and ngModel in the Forms guide.

Here's how to import the FormsModule to make [(ngModel)] available.

src/app/app.module.ts (FormsModule import)

Inside [(ngmodel)].

Looking back at the name binding, note that you could have achieved the same result with separate bindings to the <input> element's value property and input event.

That's cumbersome. Who can remember which element property to set and which element event emits user changes? How do you extract the currently displayed text from the input box so you can update the data property? Who wants to look that up each time?

That ngModel directive hides these onerous details behind its own ngModel input and ngModelChange output properties.

The ngModel data property sets the element's value property and the ngModelChange event property listens for changes to the element's value.

The details are specific to each kind of element and therefore the NgModel directive only works for an element supported by a ControlValueAccessor that adapts an element to this protocol. The <input> box is one of those elements. Angular provides value accessors for all of the basic HTML form elements and the Forms guide shows how to bind to them.

You can't apply [(ngModel)] to a non-form native element or a third-party custom component until you write a suitable value accessor , a technique that is beyond the scope of this guide.

You don't need a value accessor for an Angular component that you write because you can name the value and event properties to suit Angular's basic two-way binding syntax and skip NgModel altogether. The sizer shown above is an example of this technique.

Separate ngModel bindings is an improvement over binding to the element's native properties. You can do better.

You shouldn't have to mention the data property twice. Angular should be able to capture the component's data property and set it with a single declaration, which it can with the [(ngModel)] syntax:

Is [(ngModel)] all you need? Is there ever a reason to fall back to its expanded form?

The [(ngModel)] syntax can only set a data-bound property. If you need to do something more or something different, you can write the expanded form.

The following contrived example forces the input value to uppercase:

Here are all variations in action, including the uppercase version:

Built-in structural directives

Structural directives are responsible for HTML layout. They shape or reshape the DOM's structure , typically by adding, removing, and manipulating the host elements to which they are attached.

The deep details of structural directives are covered in the Structural Directives guide where you'll learn:

  • why you prefix the directive name with an asterisk (*) .
  • to use <ng-container> to group elements when there is no suitable host element for the directive.
  • how to write your own structural directive.
  • that you can only apply one structural directive to an element.

This section is an introduction to the common structural directives:

  • NgIf - conditionally add or remove an element from the DOM
  • NgFor - repeat a template for each item in a list
  • NgSwitch - a set of directives that switch among alternative views

You can add or remove an element from the DOM by applying an NgIf directive to that element (called the host elment ). Bind the directive to a condition expression like isActive in this example.

Don't forget the asterisk ( * ) in front of ngIf .

When the isActive expression returns a truthy value, NgIf adds the HeroDetailComponent to the DOM. When the expression is falsy, NgIf removes the HeroDetailComponent from the DOM, destroying that component and all of its sub-components.

Show/hide is not the same thing

You can control the visibility of an element with a class or style binding:

Hiding an element is quite different from removing an element with NgIf .

When you hide an element, that element and all of its descendents remain in the DOM. All components for those elements stay in memory and Angular may continue to check for changes. You could be holding onto considerable computing resources and degrading performance, for something the user can't see.

When NgIf is false , Angular removes the element and its descendents from the DOM. It destroys their components, potentially freeing up substantial resources, resulting in a more responsive user experience.

The show/hide technique is fine for a few elements with few children. You should be wary when hiding large component trees; NgIf may be the safer choice.

Guard against null

The ngIf directive is often used to guard against null. Show/hide is useless as a guard. Angular will throw an error if a nested expression tries to access a property of null .

Here we see NgIf guarding two <div> s. The currentHero name will appear only when there is a currentHero . The nullHero will never be displayed.

See also the safe navigation operator described below.

NgFor is a repeater directive — a way to present a list of items. You define a block of HTML that defines how a single item should be displayed. You tell Angular to use that block as a template for rendering each item in the list.

Here is an example of NgFor applied to a simple <div> :

You can also apply an NgFor to a component element, as in this example:

Don't forget the asterisk ( * ) in front of ngFor .

The text assigned to *ngFor is the instruction that guides the repeater process.

*ngFor microsyntax

The string assigned to *ngFor is not a template expression . It's a microsyntax — a little language of its own that Angular interprets. The string "let hero of heroes" means:

Take each hero in the heroes array, store it in the local hero looping variable, and make it available to the templated HTML for each iteration.

Angular translates this instruction into a <template> around the host element, then uses this template repeatedly to create a new set of elements and bindings for each hero in the list.

Learn about the microsyntax in the Structural Directives guide.

The let keyword before hero creates a template input variable called hero . The ngFor directive iterates over the heroes array returned by the parent component's heroes property and sets hero to the current item from the array during each iteration.

You reference the hero input variable within the ngFor host element (and within its descendents) to access the hero's properties. Here it is referenced first in an interpolation and then passed in a binding to the hero property of the <hero-detail> component.

Learn more about template input variables in the Structural Directives guide.

*ngFor with index

The index property of the NgFor directive context returns the zero-based index of the item in each iteration. You can capture the index in a template input variable and use it in the template.

The next example captures the index in a variable named i and displays it with the hero name like this.

Learn about the other NgFor context values such as last , even , and odd in the NgFor API reference .

*ngFor with trackBy

The NgFor directive may perform poorly, especially with large lists. A small change to one item, an item removed, or an item added can trigger a cascade of DOM manipulations.

For example, re-querying the server could reset the list with all new hero objects.

Most, if not all, are previously displayed heroes. You know this because the id of each hero hasn't changed. But Angular sees only a fresh list of new object references. It has no choice but to tear down the old DOM elements and insert all new DOM elements.

Angular can avoid this churn with trackBy . Add a method to the component that returns the value NgFor should track. In this case, that value is the hero's id .

In the microsyntax expression, set trackBy to this method.

Here is an illustration of the trackBy effect. "Reset heroes" creates new heroes with the same hero.id s. "Change ids" creates new heroes with new hero.id s.

  • With no trackBy , both buttons trigger complete DOM element replacement.
  • With trackBy , only changing the id triggers element replacement.

NgSwitch is like the JavaScript switch statement. It can display one element from among several possible elements, based on a switch condition . Angular puts only the selected element into the DOM.

NgSwitch is actually a set of three, cooperating directives: NgSwitch , NgSwitchCase , and NgSwitchDefault as seen in this example.

NgSwitch is the controller directive. Bind it to an expression that returns the switch value . The emotion value in this example is a string, but the switch value can be of any type.

Bind to [ngSwitch] . You'll get an error if you try to set *ngSwitch because NgSwitch is an attribute directive, not a structural directive. It changes the behavior of its companion directives. It doesn't touch the DOM directly.

Bind to *ngSwitchCase and *ngSwitchDefault . The NgSwitchCase and NgSwitchDefault directives are structural directives because they add or remove elements from the DOM.

  • NgSwitchCase adds its element to the DOM when its bound value equals the switch value.
  • NgSwitchDefault adds its element to the DOM when there is no selected NgSwitchCase .

The switch directives are particularly useful for adding and removing component elements . This example switches among four "emotional hero" components defined in the hero-switch.components.ts file. Each component has a hero input property which is bound to the currentHero of the parent component.

Switch directives work as well with native elements and web components too. For example, you could replace the <confused-hero> switch case with the following.

A template reference variable is often a reference to a DOM element within a template. It can also be a reference to an Angular component or directive or a web component .

Use the hash symbol (#) to declare a reference variable. The #phone declares a phone variable on an <input> element.

You can refer to a template reference variable anywhere in the template. The phone variable declared on this <input> is consumed in a <button> on the other side of the template

How a reference variable gets its value

In most cases, Angular sets the reference variable's value to the element on which it was declared. In the previous example, phone refers to the phone number <input> box. The phone button click handler passes the input value to the component's callPhone method. But a directive can change that behavior and set the value to something else, such as itself. The NgForm directive does that.

The following is a simplified version of the form example in the Forms guide.

A template reference variable, heroForm , appears three times in this example, separated by a large amount of HTML. What is the value of heroForm ?

If Angular hadn't taken it over when you imported the FormsModule , it would be the HTMLFormElement . The heroForm is actually a reference to an Angular NgForm directive with the ability to track the value and validity of every control in the form.

The native <form> element doesn't have a form property. But the NgForm directive does, which explains how you can disable the submit button if the heroForm.form.valid is invalid and pass the entire form control tree to the parent component's onSubmit method.

Template reference variable warning notes

A template reference variable ( #phone ) is not the same as a template input variable ( let phone ) such as you might see in an *ngFor . Learn the difference in the Structural Directives guide.

The scope of a reference variable is the entire template . Do not define the same variable name more than once in the same template. The runtime value will be unpredictable.

You can use the ref- prefix alternative to # . This example declares the fax variable as ref-fax instead of #fax .

So far, you've focused mainly on binding to component members within template expressions and statements that appear on the right side of the binding declaration . A member in that position is a data binding source .

This section concentrates on binding to targets , which are directive properties on the left side of the binding declaration . These directive properties must be declared as inputs or outputs .

Remember: All components are directives .

Note the important distinction between a data binding target and a data binding source .

The target of a binding is to the left of the = . The source is on the right of the = .

The target of a binding is the property or event inside the binding punctuation: [] , () or [()] . The source is either inside quotes ( " " ) or within an interpolation ( {{}} ).

Every member of a source directive is automatically available for binding. You don't have to do anything special to access a directive member in a template expression or statement.

You have limited access to members of a target directive. You can only bind to properties that are explicitly identified as inputs and outputs .

In the following snippet, iconUrl and onSave are data-bound members of the AppComponent and are referenced within quoted syntax to the right of the equals ( = ).

They are neither inputs nor outputs of the component. They are sources for their bindings. The targets are the native <img> and <button> elements.

Now look at a another snippet in which the HeroDetailComponent is the target of a binding on the left of the equals ( = ).

Both HeroDetailComponent.hero and HeroDetailComponent.deleteRequest are on the left side of binding declarations. HeroDetailComponent.hero is inside brackets; it is the target of a property binding. HeroDetailComponent.deleteRequest is inside parentheses; it is the target of an event binding.

Declaring input and output properties

Target properties must be explicitly marked as inputs or outputs.

In the HeroDetailComponent , such properties are marked as input or output properties using decorators.

Alternatively, you can identify members in the inputs and outputs arrays of the directive metadata, as in this example:

You can specify an input/output property either with a decorator or in a metadata array. Don't do both!

Input or output?

Input properties usually receive data values. Output properties expose event producers, such as EventEmitter objects.

The terms input and output reflect the perspective of the target directive.

Inputs and outputs

HeroDetailComponent.hero is an input property from the perspective of HeroDetailComponent because data flows into that property from a template binding expression.

HeroDetailComponent.deleteRequest is an output property from the perspective of HeroDetailComponent because events stream out of that property and toward the handler in a template binding statement.

Aliasing input/output properties

Sometimes the public name of an input/output property should be different from the internal name.

This is frequently the case with attribute directives . Directive consumers expect to bind to the name of the directive. For example, when you apply a directive with a myClick selector to a <div> tag, you expect to bind to an event property that is also called myClick .

However, the directive name is often a poor choice for the name of a property within the directive class. The directive name rarely describes what the property does. The myClick directive name is not a good name for a property that emits click messages.

Fortunately, you can have a public name for the property that meets conventional expectations, while using a different name internally. In the example immediately above, you are actually binding through the myClick alias to the directive's own clicks property.

You can specify the alias for the property name by passing it into the input/output decorator like this:

You can also alias property names in the inputs and outputs arrays. You write a colon-delimited ( : ) string with the directive property name on the left and the public alias on the right :

Template expression operators

The template expression language employs a subset of JavaScript syntax supplemented with a few special operators for specific scenarios. The next sections cover two of these operators: pipe and safe navigation operator .

The pipe operator ( | )

The result of an expression might require some transformation before you're ready to use it in a binding. For example, you might display a number as a currency, force text to uppercase, or filter a list and sort it.

Angular pipes are a good choice for small transformations such as these. Pipes are simple functions that accept an input value and return a transformed value. They're easy to apply within template expressions, using the pipe operator ( | ) :

The pipe operator passes the result of an expression on the left to a pipe function on the right.

You can chain expressions through multiple pipes:

And you can also apply parameters to a pipe:

The json pipe is particularly helpful for debugging bindings:

The generated output would look something like this

The safe navigation operator ( ?. ) and null property paths

The Angular safe navigation operator ( ?. ) is a fluent and convenient way to guard against null and undefined values in property paths. Here it is, protecting against a view render failure if the currentHero is null.

What happens when the following data bound title property is null?

The view still renders but the displayed value is blank; you see only "The title is" with nothing after it. That is reasonable behavior. At least the app doesn't crash.

Suppose the template expression involves a property path, as in this next example that displays the name of a null hero.

JavaScript throws a null reference error, and so does Angular:

Worse, the entire view disappears .

This would be reasonable behavior if the hero property could never be null. If it must never be null and yet it is null, that's a programming error that should be caught and fixed. Throwing an exception is the right thing to do.

On the other hand, null values in the property path may be OK from time to time, especially when the data are null now and will arrive eventually.

While waiting for data, the view should render without complaint, and the null property path should display as blank just as the title property does.

Unfortunately, the app crashes when the currentHero is null.

You could code around that problem with *ngIf .

You could try to chain parts of the property path with && , knowing that the expression bails out when it encounters the first null.

These approaches have merit but can be cumbersome, especially if the property path is long. Imagine guarding against a null somewhere in a long property path such as a.b.c.d .

The Angular safe navigation operator ( ?. ) is a more fluent and convenient way to guard against nulls in property paths. The expression bails out when it hits the first null value. The display is blank, but the app keeps rolling without errors.

It works perfectly with long property paths such as a?.b?.c?.d .

You've completed this survey of template syntax. Now it's time to put that knowledge to work on your own components and directives.

IMAGES

  1. Angular Assignment Help

    angular html variable assignment

  2. GitHub

    angular html variable assignment

  3. Angular

    angular html variable assignment

  4. If else in Angular HTML Template

    angular html variable assignment

  5. Angular

    angular html variable assignment

  6. Angular 12 tutorial #30 Template Reference Variable

    angular html variable assignment

VIDEO

  1. Angular Gradient

  2. Angular Signals: Untracked API

  3. 1 Introduction to Angular Front End Framework

  4. 2 Introduction to Angular TypeScript

  5. 47.0 How #angular works and various files and folders

  6. What Are Angular Forms Type of Angular Forms075

COMMENTS

  1. Angular

    Understanding template variables. Template variables help you use data from one part of a template in another part of the template. Use template variables to perform tasks such as respond to user input or finely tune your application's forms. A template variable can refer to the following: a DOM element within a template. a directive or component.

  2. html

    127. You can declare variables in html code by using a template element in Angular 2 or ng-template in Angular 4+. Templates have a context object whose properties can be assigned to variables using let binding syntax. Note that you must specify an outlet for the template, but it can be a reference to itself.

  3. Angular

    To bind to an element's property, enclose it in square brackets, [], which identifies the property as a target property. A target property is the DOM property to which you want to assign a value. To assign a value to a target property for the image element's src property, type the following code: src/app/app.component.html. content_copy.

  4. Template Variables

    Template variables help you use data from one part of a template in another part of the template. With template variables, you can perform tasks such as respond to user input or finely tune your application's forms. A template variable can refer to the following: a DOM element within a template. a directive. an element.

  5. Understanding Template Variables in Angular

    Template variables may be used on more than just HTML elements, however. If you assign one on a component, you can then use the variable to refer to the component instance. For example, assigning a template variable to a ContactCard component would let us reference its publicly accessible properties in other parts of the template:

  6. Template Variables in Angular

    Creating a template variable is very easy with Angular. Simply add a unique identifier to whatever it is you wish to reference, like so: xxxxxxxxxx. <input type="email" placeholder="Email Address" #email>. The reference in the example here is defined by the #email attribute added to the element. The name of the reference is simply email so ...

  7. Angular

    Template variables. link. Template variables help you use data from one part of a template in another part of the template. With template variables, you can perform tasks such as respond to user input or finely tune your application's forms. A template variable can refer to the following: a DOM element within a template. a directive. an element.

  8. Angular

    A template reference variable is often a reference to a DOM element within a template. It can also refer to a directive (which contains a component), an element, TemplateRef, or a web component. See the live example / descargar ejemplo for a working example containing the code snippets in this guide. Use the hash symbol (#) to declare a ...

  9. javascript

    You cannot create or set value in a variable inside interpolation { { }}, interpolation is only used to print the output (value of variable). Angular Interpolation is a way of data binding in Angular. And it will allow user to communicate between component and it's template (view). String Interpolation is a one way data binding.

  10. Angular Template Reference Variables In-Depth

    Template reference variables are cleverly implemented and can be used in various ways. The first might be to simply export a reference to an element. Here we can attach a # to an <input> and provide a variable name (hence the template reference 'variable'): <input type="text" #coffee>. You can think of this syntax as an "export".

  11. Angular

    Template statements. Template statements are methods or properties that you can use in your HTML to respond to user events. With template statements, your application can engage users through actions such as displaying dynamic content or submitting forms. See the Template syntax / download example for the syntax and code snippets in this guide.

  12. Template Reference Variable in Angular

    The Template reference variable is a reference to any DOM element, component or a directive in the Template. Use #variable to create a reference to it. We can also use #variable="exportAsName" when the component/directive defines an exportAs metadata. The template variable can be used anywhere in the template.

  13. Template Syntax

    HTML in templates. HTML is the language of the Angular template. Almost all HTML syntax is valid template syntax. The <script> element is a notable exception; it is forbidden, eliminating the risk of script injection attacks. In practice, <script> is ignored and a warning appears in the browser console. See the Security page for details.. Some legal HTML doesn't make much sense in a template.

  14. How To Use the innerHTML Property Binding in Angular

    The rendered HTML could contain malicious scripts that present a security issue. One method of addressing XSS is by restricting the kinds of HTML elements and attributes to a set of known "safe" elements and attributes. Behind the scenes, [innerHTML] uses Angular's DomSanitizer which uses a list of approved HTML elements and attributes.

  15. Angular

    Extend the HTML vocabulary of your applications with special Angular syntax in your templates. For example, Angular helps you get and set DOM (Document Object Model) values dynamically with features such as built-in template functions, variables, event listening, and data binding. Almost all HTML syntax is valid template syntax.

  16. Angular

    Learn how to use Angular interpolation and property binding to display variables in html elements. See examples and solutions from other Stack Overflow users.

  17. Angular HtmlEditor

    The following list shows how to specify the dataSource property depending on your data source: . Data Array Assign the array to the dataSource property.. Read-Only Data in JSON Format Set the dataSource property to the URL of a JSON file or service that returns JSON data.. OData Implement an ODataStore.. Web API, PHP, MongoDB

  18. Put an angular variable in an HTML attribute

    Put an angular variable in an HTML attribute. Question: In the below sample code, we can see that each message has a unique MessageSid. In the HTML code, I would like to set. How can I do this? I would like each modal to be individual to each message. MessageSid: string; Body: string; Time: string; Direction: string;

  19. javascript

    Stack Overflow Public questions & answers; Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers; Talent Build your employer brand ; Advertising Reach developers & technologists worldwide; Labs The future of collective knowledge sharing; About the company

  20. Angular

    The Angular template expression language employs a subset of JavaScript syntax supplemented with a few special operators for specific scenarios. See the live example / download example for a working example containing the code snippets in this guide.

  21. Angular

    The context against which an expression evaluates is the union of the template variables, the directive's context object—if it has one—and the component's members. If you reference a name that belongs to more than one of these namespaces, Angular applies the following precedence logic to determine the context: The template variable name.