NativeScript: load ListView.itemTemplate from XML file

Thread is closed for posting
2 posts, 0 answers
  1. Marc
    Marc avatar
    101 posts
    Member since:
    Oct 2013

    Posted 19 Jan 2017 Link to this post

    Hello,

    in one of the pages in our NativeScript app I need to dynamically build the UI within JavaScript and that page contains a TabView with a variable count of TabEntries. In each Tab, there is one ListView and I want to use the same itemTemplate in each ListView.

     

    When I build the UI in XML, I can include one template via namespace to multiple ListViews like that:

    <!-- fixed template -->
    <ListView items="{{ items}}">
        <ListView.itemTemplate>
            <StackLayout >
                <Label text="{{ name }}"/>
                <!-- ... -->
            </StackLayout>
        </ListView.itemTemplate>
    </ListView>
    <!-- using namespace  -->
    <ListView items="{{ items}}">
        <ListView.itemTemplate>
            <myNameSpace:list-template/>
        </ListView.itemTemplate>
    </ListView>

     

    Right now, I assign the the itemTemplate to my ListView as a String:

    listViewSubCategories.itemTemplate =
     `<StackLayout>
             <Label text="{{ name }}" />
    </StackLayout>`;

     

    but that's not the best solution. Is there another way to include this Template to my ListView?

    I know Angular offers the opportunity to assign a templateURL or something like that, but we use NativeScript with Vanilla JavaScript.

     

    I am thankful for any advice.

     

    Best regards

     

     

     

     

  2. Nikolay Iliev
    Admin
    Nikolay Iliev avatar
    351 posts

    Posted 24 Jan 2017 Link to this post

    Hi Marc,

    The itemTemplate can handle string or Template as a passed value. The Template interface has a factory function which means that you can create your template as follows:

    var list = new ListView(); // create or getViewById the list-view
    list.items = [5, 4, 3]; // set some mock list items
     
    list.itemTemplate = () => {
     
        // build the template layout
        var stack = new StackLayout();
        var lbl = new Label();
         
        // example for simple bind equal to XML <Label text="{{ $value }}"/>
        lbl.bind({ sourceProperty: "$value", targetProperty: "text" });
        stack.addChild(lbl);
     
        return stack;
    }
     
    page.content = list;


    Regards,
    Nikolay Iliev
    Telerik by Progress
     

    Visit the Telerik Verified Plugins Marketplace and get the custom Cordova plugin you need, already tweaked to work seamlessly with AppBuilder.

     
Back to Top