NativeScript 2.0 Custom Components and CSS - nativescript

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:
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:
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?

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%;
}

Related

radautocomplete menu pops open when navigating with bottom navigation

I have a radautocomplete in one of my pages and I'm using bottom-navigation in my app.
The first time I navigate to that page is fine, but after that, when I navigate to that page, the suggestions menu automatically pops open as if I had typed something in the autocomplete but I have not. I even put a textfields above that in my form to steal the focus but that didn't make things any better.
Here is a playground sample
In case playground breaks in the future:
App.vue
<template>
<Page actionBarHidden="true">
<BottomNavigation :selectedIndex="activePage">
<TabStrip>
<TabStripItem>
<label text="0" />
</TabStripItem>
<TabStripItem>
<label text="1" />
</TabStripItem>
</TabStrip>
<TabContentItem>
<button text="go to 1" #tap="activePage=1" />
</TabContentItem>
<TabContentItem>
<StackLayout>
<TextField v-model="textFieldValue" hint="Enter text..."
backgroundColor="lightgray" />
<RadAutoCompleteTextView ref="autocomplete"
:items="choices" backgroundColor="lightgray"
completionMode="Contains" returnKeyType="done"
width="100%" borderRadius="5" />
</StackLayout>
</TabContentItem>
</BottomNavigation>
</Page>
</template>
<script>
import {
ObservableArray
} from "tns-core-modules/data/observable-array";
import {
TokenModel
} from "nativescript-ui-autocomplete";
export default {
data() {
return {
textFieldValue: "",
choices: new ObservableArray(
["one", "two", "three"].map(r => new TokenModel(r))
),
activePage: 0
};
}
};
</script>
<style scoped>
TabContentItem>* {
font-size: 30;
text-align: center;
vertical-align: center;
}
</style>
app.js
import Vue from 'nativescript-vue';
import App from './components/App';
import RadAutoComplete from 'nativescript-ui-autocomplete/vue';
Vue.use(RadAutoComplete);
new Vue({ render: h => h('frame', [h(App)]) }).$start();
I guess the issue is specific to Android, iOS seem to work fine. You may raise an issue at Github, meanwhile a possible workaround is to set visibility on suggestion view on unloaded event, toggle it back on textChanged event.
Updated Playground Sample 1
Update
Changing visibility seems to hide the suggestion view but still occupy the same so components below auto complete field becomes inaccessible. I believe setSuggestionViewHeight(...) may solve this.
Updated Playground Sample 2

NativeScript - Passing content from Parent to Child component

I've been searching for this all over during the last 2 days so I decided to ask for help.
Imagine we have a parent component called ParentComponent and we have also a child component called SomeComponent.
SomeComponent template would be:
import {Component} from "#angular/core";
#Component({
selector: "SomeComponent",
template: `
<ActionBar title="TestApp">
</ActionBar>
<StackLayout style="margin-top:20;">
<Label text="Somenthing on top"></Label>
#CONTAINER CONTENT HERE#
<Label text="Something in the bottom"></Label>
</StackLayout>
`,
})
export class SomeComponent {}
..and ParentComponent template would be:
import {Component} from "#angular/core";
import {SomeComponent} from "../some/where/...";
#Component({
selector: "parent",
template: `
<SomeComponent>
<Label text="Something here"></Label>
<Label text="Something else here"></Label>
</SomeComponent>
`,
})
export class ParentComponent {}
Considering the aforementioned example, how can I get the content inside "< SomeComponent >" defined in my ParentComponent, to be displayed properly in the SomeComponent in the reserved "#CONTAINER CONTENT HERE#" area?
In theory it is as if I would end up with something like this:
<ActionBar title="TestApp">
</ActionBar>
<StackLayout style="margin-top:20;">
<Label text="Somenthing on top"></Label>
<Label text="Something here"></Label>
<Label text="Something else here"></Label>
<Label text="Something in the bottom"></Label>
</StackLayout>
It looks like something pretty simple that I used to do in react native, that I can't get to work on NS.
Thanks in advance.
You can use a ng-content tag to transclude the content from the parent container to the child. I believe all you need to add ng-content to your SomeContent component, which will then look like:
import {Component} from "#angular/core";
#Component({
selector: "SomeComponent",
template: `
<ActionBar title="TestApp">
</ActionBar>
<StackLayout style="margin-top:20;">
<Label text="Somenthing on top"></Label>
<ng-content></ng-content>
<Label text="Something in the bottom"></Label>
</StackLayout>
`,
})
export class SomeComponent {}
You can read more about transclusion here https://toddmotto.com/transclusion-in-angular-2-with-ng-content
Also you can see a working example inside of the slides plugin I wrote https://github.com/TheOriginalJosh/nativescript-ngx-slides/blob/master/slides/app/slides/slides.component.ts#L40

Nativescript + Angular2: RadListView binding

I'm attempting to bind an Observable to a RadListView, without using any Page properties, but appear to be doing something completely wrong. The following is a minified version of the code.
The component:
export class WeatherComponent implements OnInit {
public weather : ObservableArray<StringWrapper>;
constructor(private _weatherService : WeatherService) {
this.weather = new ObservableArray<StringWrapper>([]);
this.weather.push(<StringWrapper>{value:'Sunny'});
}
ngOnInit(): void {
this._weatherService.getDummyWeather().subscribe(
item => {
this.weather.push(item);
}
);
}
}
The XML:
<RadListView [items]="weather">
<template tkListItemTemplate let-item="item">
<StackLayout orientation="vertical">
<Label [text]="item.value"></Label>
</StackLayout>
</template>
</RadListView>
The simple data model:
export interface StringWrapper {
value : string;
}
The service:
#Injectable()
export class WeatherService {
public getDummyWeather() : Observable<StringWrapper> {
return Observable.of(<StringWrapper>{value:'Rainy'});
}
}
The service is correctly updating the model but the view is not reflecting the changes, leading me to believe the problem is located in the observable binding.
Any help would be deeply appreciated!
N.B. Checked related questions and none of the solutions helped, i.e. Nativescript RadListView not binding to source property solution causes a build error.
Change the HTML to
<RadListView [items]="weather" >
<template tkListItemTemplate let-item="item">
<StackLayout class="itemStackLayout" >
<Label class="titleLabel" [text]="item.value" textWrap="true" width="100%"></Label>
</StackLayout>
</template>
</RadListView>
Hint: Seems like stringwrapper is not need. You can use below code if it just a string array
<Label class="titleLabel" [text]="item" textWrap="true" width="100%"></Label>

Nativescript Listview with header and scroll entire page

I am using ListView with Header portion on top of it like below,
<StackLayout>
<StackLayout height="200">
<Label text="Header content goes in this section"></Label>
<StackLayout>
<ListView [items]='posts'>
<!-- template items goes here -->
</ListView>
</StackLayout>
When we scroll to list the header is sticky in this case.
Is there a option that scroll overrides header also ?.I mean that header also part of scroll.
Fr Angular-2 application you can now use tkTemplateKey deirective and create your own headers, footers, groups and other custom list-view elements.
Example can be found here
Here is the code for a list-view with header and groups.
page.component.html
<ListView [items]="countries" [itemTemplateSelector]="templateSelector" (itemTap)="onItemTapFirstList($event)" class="list-group" separatorColor="white">
<ng-template nsTemplateKey="header" let-header="item">
<Label [text]="header.name" class="list-group-item h3 bg-primary" isUserInteractionEnabled="false" color="white" fontSize="24"></Label>
</ng-template>
<ng-template nsTemplateKey="footer" let-footer="item">
<Label [text]="footer.name" class="list-group-item" backgroundColor="gray"></Label>
</ng-template>
<ng-template nsTemplateKey="cell" let-country="item">
<StackLayout class="list-group-item">
<Label [text]="country.name" class="list-group-item-heading"></Label>
<Label [text]="country.desc" class="list-group-item-text" textWrap="true"></Label>
</StackLayout>
</ng-template>
</ListView>
page.component.ts
#Component({
moduleId: module.id,
templateUrl: "./multi-line-grouped.component.html",
changeDetection: ChangeDetectionStrategy.OnPush
})
export class MultiLineGroupedListViewExampleComponent implements OnInit {
public countries: Array<any> = [];
public templateSelector = (item: any, index: number, items: any) => {
return item.type || "cell";
}
ngOnInit() {
for (let i = 0; i < mockedCounties.length; i++) {
this.countries.push(mockedCounties[i]);
}
}
onItemTapFirstList(args: ItemEventData) {
console.log(args.index);
}
}
Not sure if there's another way, but one way could be moving the header inside the listview. For that to work it needs to be in the posts Array, so you may want to transform that into some sort of wrapping class that can contain eiter a header or item row. Then create two templates inside the listview that depending on the template key render a header or an item.
For details on templates, see https://docs.nativescript.org/cookbook/ui/list-view#define-multiple-item-templates-and-an-item-template-selector-in-xml
You can use *ngFor creating the list.Here is the sample code for doing this.
<ScrollView>
<StackLayout>
//define your header over here
<Label text="hey header"></Label>
<StackLayout *ngFor="let item of <Array>">
<GridLayout columns="4*,*" rows="*,">
<Label row="0" col="0" text="hey label"></Label>
</GridLayout>
<StackLayout>
<StackLayout>
</ScollView>

multi css selectors not applying style

I have a class that when clicked is styled differently.
I tried to have the element as:
<GridLayout (tap)="onHeaderClicked()" cssClass="table-header" [class.open]="isOpen"> </GridLayout>
however when trying to apply styling to:
.table-header.open{
}
the css is not getting applied, I have now had to resort to the following syntax and have 2 methods:
<GridLayout (tap)="onHeaderClicked()" cssClass="{{isOpen ? 'table-header-open' : 'table-header-closed' }}">
and create styles for these individually
is this possible in nativescript?
In case you want to add specific style on runtime, you could use ViewChild decorator and with its help to create new property, which is pointing to the GridLayout. With this property you could change existing style properties to this element.
app.component.html
<GridLayout #container (tap)="onHeaderClicked()" rows="auto" columns="auto" width="200" height="300" cssClass="{{isOpen ? 'table-header-open' : 'table-header-closed'}}">
<Label row="0" col="0" text="sample text" textWrap="true"></Label>
</GridLayout>
app.component.ts
import {Component, ViewChild, ElementRef} from "#angular/core";
import {setTimeout} from "timer";
import {View} from "ui/core/view";
import {GridLayout} from "ui/layouts/grid-layout";
import {Color} from "color"
#Component({
selector: "my-app",
templateUrl: "app.component.html",
})
export class AppComponent {
public isOpen:boolean;
#ViewChild("container") container: ElementRef;
constructor(){
this.isOpen = true;
var that = this;
setTimeout(function() {
that.isOpen=false;
},3000);
}
public onHeaderClicked()
{
let container = <GridLayout>this.container.nativeElement;
container.color=new Color("blue");
}
}
app.css
.table-header-open{
background-color: red;
}
.table-header-closed{
background-color: green;
}

Resources