如何在NativeScript TypeScript中动态创建xml组件

时间:2018-09-12 21:19:53

标签: xml typescript nativescript

我想添加其他组件,例如布局,按钮,图像等...

这是我的xml代码,我想在ID为“聊天框”的stacklayout上添加xml:

<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>

这是我当前的打字稿代码,但是不起作用。它甚至不显示编译错误。

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 个答案:

答案 0 :(得分:1)

现在,如果您正在使用页面引用,则可以使用 getViewById 通过其唯一ID访问 Stacklayout 容器。

例如 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);;
}

或者您可以通过某些Page生命周期事件来访问Page引用

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(请注意,该演示正在使用带有TypeScript语言的NativeScript Core)。对于Angular,您可以在组件构造函数中通过DI使用Angular ViewCHild或Page引用。

相关问题