Property Binding
You can also use property binding to display variables in the HTML template. This approach is useful when you want to bind the variable to an element property, such as src for an image or value for an input field.
Syntax:
<img [src]="imageUrl" />
<input [value]="inputValue" />
Code Example:
<!-- app.component.html -->
<h1>{{ title }}</h1>
<p>Hello, {{ name }}!</p>
<img [src]="imageUrl" alt="Example Image">
// app.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Angular Data Binding';
name = 'John Doe';
imageUrl = 'https://example.com/image.jpg';
}
Output:
How to display variable from .ts file to .html file in angular 17
In Angular, when you’re working on a component, you use TypeScript files (.ts) to write the code that controls how the component behaves. On the other hand, HTML files (.html) handle how the user interface looks and gets displayed.
Table of Content
- Data Binding
- Steps to Create Angular Application
- Interpolation
- Property Binding
If you want to show a variable from the TypeScript file in the HTML file, you have to use something called data binding. Data binding basically connects the properties of your component to what gets shown on the screen, making sure everything stays in sync.