user1261710
user1261710

Reputation: 2639

Nativescript: How to make label no longer than the width of its container in a grid flexbox?

I'm writing an app with NativeScript 6.4.1 and Angular 8.

On the home page of my app, I need to have a list of buttons with a label underneath the button.

I want the container that holds the button and the text to be the same width for all. If the text is too long it will go onto the next line rather than expand the size of the parent container.

I have tried to use FlexboxLayout for this purpose but I notice that the parent containers just expand: https://play.nativescript.org/?template=play-ng&id=jbpqMk&v=5

I guess I need some flexiblity in the layout as well; maybe have the ability to configure if its 2 or 3 columns.

Would I be better off using GridLayout?

Here is a code snippet:

home.html

<FlexboxLayout backgroundColor="pink" flexWrap="wrap" justifyContent="center">
    <ns-home-button *ngFor="let n of list" name="{{ n.name }}"></ns-home-button>
</FlexboxLayout>

Desired Result:

enter image description here

Current Result:

enter image description here

Upvotes: 0

Views: 420

Answers (1)

Ian MacDonald
Ian MacDonald

Reputation: 14030

Interestingly, the cells you've shown in your demo are properly aligned as per your flow specifications. Using a GridLayout would be possible, but not really ideal. The GridLayout would need all of its rows counted and specified, which is annoying, and it would also force its children to fit within it, rather than expand based on children (like FlexboxLayout or StackLayout).

Instead, just put a width on each item. The easiest two ways to do this are by wrapping each element:

<FlexboxLayout backgroundColor="pink" flexWrap="wrap" justifyContent="center">
    <StackLayout width="33%" *ngFor="let n of list">
        <ns-home-button name="{{ n.name }}"></ns-home-button>
    </StackLayout>
</FlexboxLayout>

or by modifying the component spec:

<FlexboxLayout backgroundColor="pink" flexWrap="wrap" justifyContent="center">
    <ns-home-button width="33%" *ngFor="let n of list" name="{{ n.name }}"></ns-home-button>
</FlexboxLayout>
    @Input() width: string;
<FlexboxLayout [width]="width" ...>
    ...
</FlexboxLayout>

Upvotes: 1

Related Questions