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


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


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.


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.


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


let stackLayout: StackLayout = this.container.nativeElement;

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


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


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.


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.


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.


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