Jacob Jacobs
Jacob Jacobs

Reputation: 25

How to create xml component dynamically in nativescript typescript

I want to add another component like layout, button, image, etc...

This my xml code and I want to add xml on stacklayout which ID is "chatbox":

<GridLayout orientation="vertical" rows="*, auto" columns="auto,*, auto"> 
    <ScrollView row="0" colSpan="3" col="0">
         <StackLayout id="chatbox">
              // I want to add XML component here dynamically
         </StackLayout>
    </ScrollView>

Here's my current typescript code but it doesn't work. It doesn't even show compile error.

export function onSendButtonTap(args: EventData){

const button = <Button>args.object;
const bindingContext = <HomeViewModel>button.bindingContext;

const page = <Page>args.object;
const stack = new StackLayout();
stack.getViewById("chatbox");
const label = new Label();
label.text = "label";
stack.addChild(label);;
bindingContext.sendMessage();                }

Upvotes: 1

Views: 2298

Answers (1)

Nick Iliev
Nick Iliev

Reputation: 9670

Now if you are using page reference you can use getViewById to access the Stacklayout container via its unique ID.

For example XML

<GridLayout rows="100, *">
    <Button row="0" text="Tap to add Label" tap="onButtonTap" />
    <StackLayout row="1" id="chatbox">
        // When you tap the button the label will be added here
    </StackLayout>
</GridLayout>

TypeScript

onButtonTap(args: EventData): void {
    console.log("Button was pressed");
    const myButton = <Button>args.object;
    const page = myButton.page; // getting page reference via the button object

    const stack = <StackLayout>page.getViewById("chatbox");
    const label = new Label();
    label.text = "My New Label";
    stack.addChild(label);;
}

Or you could access the Page refence via some of the Page lifecycles events

XML

<Page loaded="pageLoaded" class="page">

TypeScript

export function pageLoaded(args: EventData) {
    let page = <Page>args.object;
    const stack = <StackLayout>page.getViewById("chatbox");
    const label = new Label();
    label.text = "My New Label";
    stack.addChild(label);;
}

Playground demo here (note that the demo is using NativeScript Core with TypeScript language). For Angular, you could use Angular ViewCHild or Page reference via DI in the componentes constructor.

Upvotes: 4

Related Questions