0
votes

I'm having an issue with NativeScript 2.0 CSS and custom components. There seems to be a giant gap in my knowledge and I'm missing something vital that is non-obvious.

Take an empty NS 2.0 app created with

$ tns create test --ng

Delete the contents of app.css (to prevent side effects).

Change app.component.ts:

import {Component} from "@angular/core";

@Component({
    selector: "my-app",
    template: `
    <StackLayout orientation="vertical">
        <Label text="Label in first StackLayout"></Label>
        <StackLayout orientation="vertical" 
                     style="width: 80%;background-color: red;">
            <Label text="Label in second StackLayout"></Label>
        </StackLayout>
    </StackLayout>
    `,

})
export class AppComponent {}

Pretty basic stuff. Produces the following expected result:

Expected result


Let's try to convert that inner StackLayout into a reusable component.

custom.component.ts

import {Component} from "@angular/core";

@Component({
    selector: "Custom",
    template: `
    <StackLayout orientation="vertical" 
                 style="width: 80%;background-color: red;">
        <Label text="Label in second StackLayout"></Label>
    </StackLayout>
    `,

})
export class CustomComponent {}

Change the app.component.ts

import {Component} from "@angular/core";
import {CustomComponent} from "./custom.component"

@Component({
    selector: "my-app",
    directives: [CustomComponent],
    template: `
    <StackLayout orientation="vertical">
        <Label text="Label in first StackLayout"></Label>
        <Custom></Custom>
    </StackLayout>
    `,

})
export class AppComponent {}

Now the output looks like this:

enter image description here

The background color is applied but the width is not.

I even tried:

<Custom style="width: 80%;"></Custom>  /* Does this even make sense? */

to no avail.

I realize percentages are experimental but suspect the error is in my code rather than NativeScript.

Where did I go wrong?

1

1 Answers

3
votes

I reviewed your code in the given code snippet and found that it could be NativeScript issue. At the moment changing the width of the StackLayout in your CustomView using inline style will be working only on Android. To change the width of your CustomView using % for both platform at the moment you should setup this property in your css file and bind cssClass property.

custom.component.ts

import {Component} from "@angular/core";

@Component({
    selector: "Custom",
    template: `
    <StackLayout orientation="vertical" 
                 [cssClass]="styleView" style="background-color: red;">
        <Label text="Label in second StackLayout"></Label>
    </StackLayout>
    `,

})
export class CustomComponent {

      public styleView="customViewStyle";

}

app.css

.customViewStyle{
    width:80%;
}