1

I am trying to change the width of some Switch elements in NativeScript with Angular because they are too small in my opinion. I have found that there is no way to do this through NativeScript's CSS subset so that means I have to make the change to the native object itself.

To do this I have added a template reference variable to each one of the switches in my template like this:

<Switch #switch checked="false"></Switch>

Then in my class I try to access their android and nativeView properties like this:

@Component({
  selector: "Settings",
  moduleId: module.id,
  templateUrl: "./settings.component.html"
})
export class SettingsComponent implements AfterViewInit {

  @ViewChildren("switch") switches: QueryList<ElementRef>;

  constructor(public calc: CalculationService) {
  }

  ngAfterViewInit() {
    console.log("afterViewInit switches: ", this.switches.length);

    if(isAndroid) {
      this.switches.forEach(
        (item) => {
          const nelem = item.nativeElement;
          console.log(nelem.android);
          console.log(nelem.nativeView);
        }
      );
    }
  }
}

But the two console.log statements where I'm accessing them just print undefined. How do I get the native view of the switches?

0

1 Answer 1

4

The Switch is a NativeScript's component and not Angular. The thing is that the Angular abstraction is on top of the mobile one so some native mobile elements might not be loaded when the Angular lifecycles are triggered.

To resolve that make sure you are using NativeScript's lifecycles to gett reference to nativeScript's mobile components.

You can achieve that in the following way:

import { Component, ViewChildren, QueryList, ElementRef} from "@angular/core";
import { isAndroid } from "platform";
import { Page } from "ui/page";

@Component({
    selector: "ns-items",
    moduleId: module.id,
    templateUrl: "./items.component.html",
})
export class ItemsComponent {
    @ViewChildren("switch") switches: QueryList<ElementRef>;

    constructor(private _page: Page) {
        this._page.on("loaded", () => {
            console.log("afterViewInit switches: ", this.switches.length);

            if (isAndroid) {
                this.switches.forEach(
                    (item) => {
                        const nelem = item.nativeElement;
                        console.log(nelem.android);
                        console.log(nelem.nativeView);
                    }
                );
            }
        })
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks this worked, but where can I find the list of page events? I can't find it anywhere in the NativeScript docs.
Apart from that any UI element and layout has loaded and unloaded event

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.