Show TOC

Programmatically Instantiating XML FragmentsLocate this document in the navigation structure

For each fragment type, SAPUI5 provides a method that can be used to programmatically instantiate a fragment.

Context

To give an example of a programmatic instantiation of a XML fragment, you first have to define one. The following code presents an example definition:

<Button xmlns= "sap.ui.commons" id= "btnInFragment" text= "Hello World" />

This fragment can be instantiated from a controller as follows:

var myButton = sap.ui.xmlfragment( "my.useful.VerySimpleUiPart" );
Note

This specific fragment does not use a controller; if controls inside a fragment needs methods that are to be defined in a controller, the controller has to be referred to in an additional parameter.

Fragments can be instantiated from JSViews, as well. Fragments of any type can be used within views of any type.

If XML fragments are used within XML views, giving the view ID as fragment ID will allow calling this.byId(…) in the view’s controller to retrieve controls inside the fragment. The following code inside the controller will instantiate the above fragment with the Button and then again retrieve the Button:
var myButton = sap.ui.xmlfragment(this.getView().getId(), "my.useful.VerySimpleUiPart" );
var theSameButton = this.byId("btnInFragment"); // returns the button in the fragment