How to create xml component dynamically in nativescript typescript

让人想犯罪 __ 提交于 2020-02-03 02:04:46

问题


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();                }

回答1:


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.



来源:https://stackoverflow.com/questions/52303634/how-to-create-xml-component-dynamically-in-nativescript-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!