Skip to content

injectAttribute

injectAttribute is a small utility built on top of HostAttributeToken that lets you read host attributes through inject().
It’s ideal for static, initialization-time configuration, since—unlike input() attributes are resolved once and never updated later.

import { injectAttribute } from 'ngxtension/inject-attribute';
@Component({
selector: 'app-divider',
standalone: true,
})
class Divider {
size = injectAttribute('size', 'sm');
}
<app-divider size="lg" />

If the size attribute is not provided, it defaults to 'sm'.

Use injectAttribute.required() when an attribute must be provided:

@Component({
selector: 'app-card',
standalone: true,
})
class Card {
variation = injectAttribute.required<string>('variation');
}
<app-card variation="primary"></app-card>

If the attribute is missing, Angular throws an error: NG0201: No provider for HostAttributeToken variation found

Since host attributes are always strings, use the transform option to convert them to other types:

const numberAttribute = (value: string) => Number(value);
const booleanAttribute = (value: string) => value !== null;
@Component({
selector: 'app-paginator',
standalone: true,
})
class Paginator {
// Convert string to number
pageSize = injectAttribute('pageSize', 10, {
transform: numberAttribute,
});
// Convert string to boolean
disabled = injectAttribute('disabled', false, {
transform: booleanAttribute,
});
}
<app-paginator pageSize="20" disabled />