user3496167
user3496167

Reputation: 175

Is it possible to get children in custom component?

Is it possible to get children in custom component?

<myCustomComponent>
    <Label #id1 text="ID 1"></Label>
    <Label #id2 text="ID 2"></Label>
</myCustomComponent>

Is there a way to get the reference of these two Lable to get them positioned in a GridLayout in my custom component?

Upvotes: 3

Views: 2646

Answers (2)

Nick Iliev
Nick Iliev

Reputation: 9670

Apart from the option with getViewById() there are several options to see the a layout's children or their index and also to add, remove, insert and reset children.

e.g. page.xml

<Page xmlns="http://schemas.nativescript.org/tns.xsd" navigatingTo="navigatingTo">
    <StackLayout id="st" class="p-20">
        <Label id="lbl-title" text="Tap the button" class="h1 text-center"/>
        <Button text="TAP" tap="{{ onTap }}" class="btn btn-primary btn-active"/>
        <Label text="{{ message }}" class="h2 text-center" textWrap="true"/>
    </StackLayout>
</Page>

page.ts

let page = <Page>args.object;
let stack = <StackLayout>page.getViewById("st");
let label = <Label>page.getViewById("lbl-title");

console.log("page.content: " + page.content); // page.content: StackLayout<st>@file:///app/main-page.xml:19:5;

console.log("stack.getChildrenCount(): " + stack.getChildrenCount()) // 3
console.log("stack.getChildAt(1): " + stack.getChildAt(1)); // stack.getChildAt(1): Button(5)@file:///app/main-page.xml:21:9;
console.log("stack.getChildIndex(label): " + stack.getChildIndex(label)); // 0

console.log("stack.parent: " + stack.parent); // stack.parent: Page(1)@file:///app/main-page.xml:7:1;

var newlabel = new Label();
newlabel.text = "new Label";
stack.addChild(newlabel);

More about all supported methods here

Upvotes: 7

BinaryNate
BinaryNate

Reputation: 81

The view class has a getViewById() method for this purpose.

In my-component.xml:

<StackLayout loaded="onLoaded">
    <Label id="label1" text="ID 1" mycustomattribute="Hi there."></Label>
    <Label id="label2" text="ID 2"></Label>
</StackLayout>

In my-component.js:

exports.onLoaded = function(args) {

    let view = args.object;
    let label1 = view.getViewById('label1');
    console.log(label1.mycustomattribute);
    // > "Hi there."
};

Upvotes: 2

Related Questions