Q: Load a Component to replace/insert on an action


#1

Hi everyone

Maybe the question is very simple to answer but I am not seeing atm ^^’

How would you go ahead having e.g. a basic layout with a “content container” element that you would like to fill/change with different content depending on e.g. a button tab?

Thanks a lot in advance


#2

If you want to replace everything inside a Page / ContentView programmatically, use

page.content = InstanceOfYourComponent;

If it’s a layout - let’s say stack layout here,

stackLayout.removeChildren(); // removes all existing child components
stackLayout.addChild(child); // adds new component

Syntax may vary based on layout, check docs for more info.

If your requirement is more of just showing or hiding components, should be more easy using visibility property.


#3

Hey @manojdcoder

Thanks for that. Hmm, when I got myself the StackLayout and tried to call addChild() I got an error:

JS: ERROR Error: [object Object] is not a valid View instance.

with

@ViewChild("container") public container: ElementRef;

...

let stackLayout: StackLayout = this.container.nativeElement;
stackLayout.addChild(xyz);

This is why I thought maybe there is a different way.

Thanks

PS: Yeah, visibility switch was my second guess in rearranging the layout ^^


#4

If xyz is a proper view element it should work. Post the code where xyz is coming from or the best way could be sharing a playground example for us to help.


#5

Hey @manojdcoder

Yeah, valid point and I think that is where my error/problem in understanding is coming from ^^’ Sorry about that.

So, I tried to load a component via builder:

        let xyz = builder.load({
            path: "~/view/detail.component",
            name: "Detail"
        });

This is probably the wrong part. So, probably the better questions would have been: How can I load and add a different component with everything to it?

Sorry again about not being specific enough.


#6

I think you are confusing Angular with NativeScript Core. There are better and easier ways to load a component in Angular. A very easy solution could be placing your component selector in your template with a ngIf and load it when you want.


#7

Hey @manojdcoder

Yeah, probably. Mixing up/Coming from a different background not fully embracing the given structure.

Thanks for the ngIf* suggestion, I think this will be what I’ll try now. Sounds the most reasonable and fitting my idea.

Thanks again and sorry about taking up your time ^^’