HTML Integration with Angular
By the end of this lesson you will be able to predict the DOM an Angular template produces, choose between property and attribute bindings, stop component host elements from breaking lists and tables, spot dangerous sanitiser bypasses, and build Reactive Forms with properly labelled, announced errors.
What you should know first: HTML in Templates & Frameworks, HTML Integration with React, Custom Elements, Attribute Reflection and Accessible Form Error Handling. Angular itself is taught in the Angular tutorial; this lesson looks only at the HTML it outputs.
Versions: the current release on 15 November 2026 is Angular 22 (@angular/core 22.2.6, Angular CLI 22.2.7 on npm). The outputs below are real. A demo app was generated with ng new, built with ng build and opened in Chrome, and the DOM was copied from the page. (The CLI needs Node.js 22.22.3 or 24.15 or newer, so check node -v first.) Angular cannot run inside the course editor, so the runnable examples use that captured HTML.
A template is compiled, not copied
Angular's compiler turns each component template into JavaScript instructions at build time. The browser never sees {{ }}, [ ] or ( ); it sees the DOM those instructions create. Think of a tailor in Lucknow working from a pattern: the chalk marks guide the cutting, but the customer receives only the finished kurta.
This template:
<h1>Hello {{ city() }}</h1>
<button type="button" [attr.aria-expanded]="open()" [aria-label]="'Menu for ' + city()"
[disabled]="false">Menu</button>
<input id="p1" [value]="city()">
<input id="p2" [attr.value]="city()">produced this DOM in the production build, with city set to "Kochi" and open to false:
<app-root ng-version="22.2.6"><h1>Hello Kochi</h1> <button type="button" aria-label="Menu for Kochi" aria-expanded="false">Menu</button> <input id="p1"><input id="p2" value="Kochi"> ...
Read it carefully:
{{ }}became plain, escaped text.[disabled]="false"set thedisabledproperty to false, so no attribute appears.[value]also set a property. The box shows "Kochi", but the element has novalueattribute.[attr.value]wrote a real attribute instead.[attr.aria-expanded]wrotearia-expanded="false". ARIA states must be attributes, and the string"false"is what screen readers need.[aria-label]withoutattr.also worked. Angular 20.2 and later accept ARIA bindings directly; older projects need[attr.aria-label], which still works everywhere.(click)handlers leave nothing in the HTML, like Vue's@click. They add no role and no keyboard support, so put them on<button>or<a>.
The difference between properties and attributes is the one from Attribute Reflection: an attribute is the label printed on a packet, a property is today's reading on the scale. Accessibility tools, CSS attribute selectors and server rendering see attributes, so bind ARIA, colspan and data-* with attributes. More in Data Binding & Events.
[(ngModel)]="name" is two-way binding: a property binding plus an (ngModelChange) event, from FormsModule. Like Vue's v-model, it never creates a <label>; that is still your job.
Control flow leaves no wrapper elements
The built-in blocks @if, @for and @switch (added in Angular 17) replace the older *ngIf, *ngFor and ngSwitch directives, which are deprecated. See Control Flow.
<ul>
@for (stop of stops(); track stop.code) {
<li>{{ stop.name }}</li>
} @empty {
<li>No stops today</li>
}
</ul>Blocks add no elements, so the <ul> keeps only <li> children and stays valid. Angular marks each block with an empty comment (<!----> in our production build, <!--container--> in development), which it uses as an anchor when it adds or removes content. track is required: it tells Angular which DOM node belongs to which item, so a re-ordered list moves existing <li> elements, with their focus, instead of rebuilding them. Keep the @empty content inside the same parent as a valid child, here an <li>.
Host elements: the hidden extra tag
Every component has a host element: the tag named by its selector. A component with selector: 'app-stop' really puts an <app-stop> element in the page, and its template goes inside it. That is an extra wrapper you never wrote.
Step 1: render railway stops with an element selector.
@Component({
selector: 'app-stop',
template: `{{ name() }}`,
})
export class StopTag {
name = input.required<string>();
}<ul>
@for (stop of stops(); track stop.code) {
<app-stop [name]="stop.name" />
}
</ul><ul><app-stop>Pune Jn</app-stop><app-stop>Lucknow</app-stop><!----></ul>
A <ul> may contain only <li> (and script-supporting elements). Here it has none, so assistive technology reports an empty list, and because unknown elements are display: inline, the stops run together on one line. Putting an <li> inside the component template does not help: it would sit inside <app-stop>, still not a direct child of <ul>.
Step 2: use an attribute selector, so the host element is the <li>:
@Component({
selector: 'li[app-stop-item]',
template: `{{ name() }}`,
})
export class StopItem {
name = input.required<string>();
}<ul>
@for (stop of stops(); track stop.code) {
<li app-stop-item [name]="stop.name"></li>
}
</ul><ul><li app-stop-item="">Pune Jn</li><li app-stop-item="">Lucknow</li><!----><!----></ul>
The same trick fixes table rows (tr[app-fare-row]), buttons (button[app-icon-button]) and links. Step 3: compare both outputs in a browser.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Angular host elements in a list</title>
<style>
body { font-family: system-ui, sans-serif; margin: 16px; }
pre { background: #f4f4f4; padding: 8px; white-space: pre-wrap; }
</style>
</head>
<body>
<h2>Element selector: app-stop</h2>
<ul id="a"><app-stop>Pune Jn</app-stop><app-stop>Lucknow</app-stop><!----></ul>
<h2>Attribute selector: li[app-stop-item]</h2>
<ul id="b"><li app-stop-item="">Pune Jn</li><li app-stop-item="">Lucknow</li><!----><!----></ul>
<pre id="out"></pre>
<script>
const lines = [];
for (const id of ["a", "b"]) {
const list = document.getElementById(id);
const kids = [...list.children];
const items = kids.filter((el) => el.localName === "li");
const wrong = kids.filter((el) => el.localName !== "li").map((el) => "<" + el.localName + ">");
lines.push("List " + id + ": " + items.length + " list items" +
(wrong.length ? ", invalid children: " + wrong.join(" ") : ", all children valid") +
", first child display: " + getComputedStyle(kids[0]).display);
}
document.querySelector("#out").textContent = lines.join("\n");
</script>
</body>
</html>List a shows no bullets and reports 0 list items with two invalid children, displayed inline. List b has 2 list items, displayed as list-item.
What about :host { display: contents; }? It removes the host's box from layout, not the element from the DOM, so the list is still invalid HTML. Older browsers also dropped elements with display: contents from the accessibility tree, so never use it on anything with a role or focus. Use attribute selectors for list items, rows and controls, and :host { display: block; } for ordinary layout wrappers.
Sanitisation and the bypass functions
Angular treats [innerHTML], [href], [src] and [style] as risky and sanitises values it does not trust. We bound this review text, which hides a script in an image error handler:
review = signal(`<b>Great</b> food <img src=x onerror="console.log('bypass ran')">`);
trusted = this.sanitizer.bypassSecurityTrustHtml(`<b>Bold</b> <img src=x onerror="console.log('bypass ran')">`);<div [innerHTML]="review()"></div>
<div [innerHTML]="trusted"></div><div><b>Great</b> food <img src="x"></div>
<div><b>Bold</b> <img src="x" onerror="console.log('bypass ran')"></div>The first onerror was removed, and the development build logged WARNING: sanitizing HTML stripped some content, see https://angular.dev/best-practices/security#preventing-cross-site-scripting-xss. The second went through DomSanitizer.bypassSecurityTrustHtml(), so it kept its handler, and the console printed bypass ran. The other bypass methods (bypassSecurityTrustUrl, ResourceUrl, Style and Script) switch off checks the same way.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sanitised vs bypassed HTML</title>
<style>
body { font-family: system-ui, sans-serif; margin: 16px; }
.box { border: 1px solid #999; padding: 8px; margin-block: 8px; }
#log { color: #b71c1c; }
</style>
</head>
<body>
<h1>Sanitised and bypassed output, side by side</h1>
<div class="box" id="safe"></div>
<div class="box" id="bypassed"></div>
<p id="log" aria-live="polite"></p>
<script>
// The image error handler writes to the page instead of the console
const payload = "document.getElementById('log').textContent += 'Script from the review ran. '";
document.getElementById("safe").innerHTML =
'<b>Great</b> food <img src="x" alt="">';
document.getElementById("bypassed").innerHTML =
'<b>Bold</b> <img src="x" alt="" onerror="' + payload + '">';
</script>
</body>
</html>Only the bypassed box makes the red message appear. Treat every bypassSecurityTrust... call as a security review item: never pass it user input, and prefer fixing the content over trusting it. Angular also works with Trusted Types; Security: XSS, Sanitisation & CSP covers the setup.
Reactive Forms: labels and errors are still yours
Our form template had a normal <label for> and <input id>. Look at the rendered form tag:
<form novalidate="" class="ng-untouched ng-pristine ng-invalid"> <label for="mobile">Mobile number</label> <input id="mobile" type="tel" formcontrolname="mobile" autocomplete="tel" aria-describedby="mobile-error" aria-invalid="false" class="ng-untouched ng-pristine ng-invalid">
Angular's forms modules add novalidate to every <form>, so the browser's own error bubbles never appear (add ngNativeValidate to keep them). The ng-* classes are for your CSS. Nothing tells a screen reader that the field is wrong, so you build that part:
@Component({
selector: 'app-otp-form',
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form" (ngSubmit)="send()">
<label for="mobile">Mobile number</label>
<input id="mobile" type="tel" formControlName="mobile" autocomplete="tel"
[attr.aria-invalid]="showError() ? 'true' : null"
[attr.aria-describedby]="showError() ? 'mobile-error' : null">
<p id="mobile-error" class="error" aria-live="polite">
@if (showError()) { Enter a 10-digit mobile number. }
</p>
<button type="submit">Send OTP</button>
</form>`,
})
export class OtpForm {
submitted = signal(false);
form = new FormGroup({
mobile: new FormControl('', { nonNullable: true,
validators: [Validators.required, Validators.pattern(/^[6-9]\d{9}$/)] }),
});
showError() {
const c = this.form.controls.mobile;
return c.invalid && (c.touched || this.submitted());
}
send() {
this.submitted.set(true);
if (this.form.invalid) document.getElementById('mobile')?.focus();
}
}The error paragraph always exists, so its live region is ready before the text arrives. null removes aria-invalid and aria-describedby until there is an error. On a failed submit, focus moves to the field. The newer Signal Forms change the API, not this HTML.
The CDK a11y toolkit, briefly
For widgets that HTML lacks, @angular/cdk/a11y supplies behaviour without styling: cdkTrapFocus keeps Tab inside a panel, LiveAnnouncer speaks messages through a live region, FocusMonitor tells keyboard focus from mouse focus, and ListKeyManager adds arrow-key movement to menus and listboxes. A newer package, Angular Aria (@angular/aria), offers unstyled accessible directives for tabs, menus and comboboxes. Prefer native elements first (<dialog>, <details>, <select>), then these. See Angular Material, CDK & Accessibility.
Common mistakes
- Element selectors for
<li>,<tr>or<option>components. Use attribute selectors. [value]when you expect an attribute. Properties do not appear in the HTML.(click)on<div>. Use<button type="button">.bypassSecurityTrustHtmlon user content. It switches off the sanitiser.- Relying on browser validation in Angular forms.
novalidateis added; render your own errors.
Interview questions
1. What is the difference between [value] and [attr.value] in Angular?
[value] sets the DOM property, so the input shows the value but no value attribute appears. [attr.value] sets the HTML attribute. Use attribute bindings for ARIA, colspan and anything tools read from markup.
2. Why does track matter in @for?
It gives each item an identity, such as an id, so Angular can reuse and move DOM nodes when the list changes instead of recreating them. That is faster and keeps focus and input state on the right element. Angular requires it.
3. A component with selector app-row is used inside <tbody>. What goes wrong and how do you fix it?
The <app-row> host element becomes a child of <tbody>, which may contain only <tr>, so the table is invalid and its semantics break. Use an attribute selector such as tr[app-row] so the host element is the <tr>.
4. Is [innerHTML] safe in Angular?
Angular sanitises it, removing scripts and event handler attributes and logging a warning in development. It becomes unsafe when you pass a value through DomSanitizer.bypassSecurityTrustHtml() or similar, which skips the check.
5. Why do Angular forms not show the browser's validation bubbles?
The forms modules add novalidate to every <form>, so Angular can manage validation itself. You must display errors yourself and connect them with aria-describedby and aria-invalid, or add ngNativeValidate to get native behaviour back.
Key points
- Angular compiles templates; only real elements, attributes and text reach the DOM.
- Property bindings change DOM properties;
[attr.x]writes attributes. Angular 20.2+ also binds[aria-*]directly. @if,@for(with requiredtrack) and@switchadd only comment anchors, never wrapper elements.- Element selectors add a host element; use attribute selectors for
<li>,<tr>and controls. [innerHTML]is sanitised; everybypassSecurityTrust...call is a risk.- Angular adds
novalidateto forms, so labels, error text,aria-invalidand focus are your job.
Exercise
Rohan's canteen app in Pune has a MenuRowComponent with selector: 'app-menu-row' used as <table><tbody>@for (d of dishes(); track $index) { <app-menu-row [dish]="d" /> }</tbody></table>, an "Info" <span (click)="toggle()"> that shows a note with @if, and a Reactive Form whose quantity input has a placeholder but no label. Rewrite the component selector, the table template, the toggle and the quantity field so the output is valid, keyboard accessible and announces errors.
Show solution
@Component({
selector: 'tr[app-menu-row]',
template: `<th scope="row">{{ dish().name }}</th><td>₹{{ dish().price }}</td>`,
})
export class MenuRow {
dish = input.required<{ id: number; name: string; price: number }>();
}<table>
<caption>Today's menu</caption>
<tbody>
@for (d of dishes(); track d.id) {
<tr app-menu-row [dish]="d"></tr>
}
</tbody>
</table>
<button type="button" [attr.aria-expanded]="infoOpen()" aria-controls="info"
(click)="infoOpen.set(!infoOpen())">Info</button>
<p id="info" [hidden]="!infoOpen()">Orders close at 2 pm.</p>
<form [formGroup]="form" (ngSubmit)="order()">
<label for="qty">Quantity</label>
<input id="qty" type="number" min="1" max="10" formControlName="qty"
[attr.aria-invalid]="qtyError() ? 'true' : null"
[attr.aria-describedby]="qtyError() ? 'qty-error' : null">
<p id="qty-error" aria-live="polite">@if (qtyError()) { Choose 1 to 10 plates. }</p>
<button type="submit">Order</button>
</form>The attribute selector makes each host a real <tr>, track d.id uses a stable key, and a <button> with aria-expanded replaces the clickable <span>. The note uses the hidden property so aria-controls always finds it. The quantity input gets a visible label and an error linked with aria-describedby.
Quick Quiz
1. Which binding writes an aria-expanded attribute in every Angular version?
The attr. prefix always writes an attribute; direct [aria-*] bindings need Angular 20.2 or later.
2. What does @if leave in the DOM when its condition is false?
Control flow blocks add no wrapper elements, just a comment Angular uses as an anchor.
3. A component should render as a list item. Which selector keeps the <ul> valid?
With an attribute selector, the host element is the <li> itself.
4. Why do Angular forms skip the browser's validation bubbles?
The forms modules add novalidate; use ngNativeValidate to keep native bubbles.
Learn HTML with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
