NativeScript + Angular2 - SegmentedBar绑定

时间:2016-07-07 11:25:10

标签: typescript angular nativescript

我几个小时都遇到过这个错误。当我运行应用程序时,IOS模拟器只显示一个白页,似乎没有任何东西被加载。我无法弄清楚出了什么问题。我想用分段栏制作一个页面。这是我的' menu.component.ts '文件代码:

import {Observable} from 'data/observable';
import {Component} from "@angular/core";

@Component({
  selector: "menu",
  templateUrl: "./components/menu/menu.html",
})

export class MenuComponent extends Observable {
  public selectedItem: string;
  public items: Array<any> = [
   { title: 'Home' },
   { title: 'G+'   },
   { title: 'Sync' }
  ];

  constructor() {
   super();
   this.selectedItem = `Selected: ${this.items[0].title}`;
}

public selectSegment(e: any) {
  this.set('selectedItem', `Selected: ${this.items[e.newIndex].title}`);
  }
}

和我的&#39; menu.html &#39;文件:

<SegmentedBar items="{{items}}" selectedIndexChanged="{{selectSegment}}" ></SegmentedBar>
<Label text="{{selectedItem}}" ></Label>

1 个答案:

答案 0 :(得分:2)

以下代码来自http://www.nativescriptsnacks.com/snippets/2016/06/22/angular-segmentedbar.html 稍作修改。

总的来说,您使用的是NativeScript Core绑定语法,而不是nativeScript + Angular-2绑定模型,它应该是这样的。

<SegmentedBar #tabs [items]="items" [selectedIndex]="selectSegment"></SegmentedBar>

有关NativeScript + Angular-2 here

中数据绑定的更多信息

// #tabs 是为您的组件提供ID的方式(等于id =&#34;标签&#34;)

以下是来自nativescriptsnacks.com的工作示例(原始代码的一些细微更改)

    import {Component, OnInit, OnDestroy, AfterViewInit, ViewChild, ElementRef} from '@angular/core';

    import {Page} from 'ui/page';
    import {SegmentedBar, SegmentedBarItem, SelectedIndexChangedEventData} from 'ui/segmented-bar';

    @Component({
        selector: 'tabs',
        template: '<SegmentedBar #tabs [items]="items" [selectedIndex]="selectedIndex"></SegmentedBar>'
    })
    export class TabsComponent implements OnInit, OnDestroy, AfterViewInit {
        selectedIndex: number;
        items: Array<any>;

        @ViewChild("tabs") tabs: ElementRef; // equal to getViewById() in NativeScript core

        constructor(private page: Page) {
            this.selectedIndex = 0;
            this.items = [{ title: 'First' }, { title: 'Second' }, { title: 'Third' }];
        }
        ngOnInit() {

        }
        ngAfterViewInit() {
            this.tabs.nativeElement.on(SegmentedBar.selectedIndexChangedEvent, (args: SelectedIndexChangedEventData) => {
                switch (args.newIndex) {
                    case 0:
                        console.log('first selected')
                        break;
                    case 1:
                        console.log('second selected')
                        break;
                    case 2:
                        console.log('third selected')
                        break;
                }
            })
        }
        ngOnDestroy() { }
    }