Content projection
<ng-content> lets a component wrap content that its parent passes in. Cards, labels and every UI component are built this way. It works on Lynx, with three rules that come from Lynx's elements.
The Lynx rules
- Projected text belongs inside a
<text>. Lynx draws text only in a<text>. If your component takes text, put the<ng-content>inside a<text>, so your styles reach it. Text projected into a<view>still shows, in a<text>of its own that takes the text styles of its ancestors' classes. - A nested
<text>is inline. When the parent passes<text>elements into your<text>, they flow as styled runs, like<span>s. - The host element is a real box.
<app-card>becomes a plain, unstyled<view>in the layout, between the parent and your template. Every static attribute the parent writes on it, such asclass="mb-2", lands on that host. When the component must fill or stretch, or takes aclass, style the host rather than a view inside it: see Make the host the element.
Project into a view
src/app/card.ts
- Pass elements, not bare text, into a component that projects into a
<view>. The parent wraps its words in<text>.
Project text
src/app/card-title.ts
- Bare text works here, because it lands inside the component's
<text>. - Nested
<text>styles part of the text. The second usage renders "Order #1042" on one line, with the number muted.
Fill the parent from the host
src/app/panel.ts
- Put sizing on the host. A
flex-1on an inner view does nothing if the unstyled host around it sizes to its content. - A component with no content needs host sizing most. With nothing inside, its host can collapse to zero size, hiding everything in it.
Make the host the element
src/app/card-title.ts
- One element, styled once. Angular puts
class="mb-2"on the host whatever the component does with it. With the classes bound on the host, and no<text>inside, the margin applies once. registerHostElement()picks the element. A host is a<view>otherwise; text has to be in a<text>. SeeregisterHostElement().- A view-shaped component needs only the
hostbinding. Its host is already a view: bind the classes there and drop the wrapper<view>. - Other attributes land on the host too. If a
placeholderinput is meant for an inner<input>, remove the host's copy withhost: { '[attr.placeholder]': 'null' }.
Named slots
src/app/badge.ts
select works as on the web, including inside a <text>.
Conditional projection
src/app/expandable-label.ts
@if and @for work around projected content, inside a <view> or a <text>.
Content queries
src/app/item-list.ts
contentChild() and contentChildren() find projected elements and components, as on the web. With read: ElementRef, you get the Lynx element, not a DOM node.
Related
- Elements and layout: the
<text>and layout rules - Content projection on angular.dev
