【问题标题】:In angular2 & nativescript the *ngFor display array's elements on top of each other在 angular2 和 nativescript 中,*ngFor 将数组的元素相互叠加
【发布时间】:2017-06-25 09:42:44
【问题描述】:

我正在使用用户的输入填充一个数组,并希望在同一页面上呈现该数组中的数据。我正在使用 *ngFor 来做到这一点,但它会在彼此之上显示元素。 html 是:

<Gridlayout class="main-container" columns="auto" rows="auto,auto,auto">
    <StackLayout  exampleTitle toggleNavButton row="0" class="set-hour">
        <!-- >> creating-timepicker-html -->
            <timePicker class="example-container" #timePicker (loaded)="configure(timePicker)" verticalAlignment="center"></timePicker>
            <Button text="Add hour" (tap)="onTap()"></Button>

        <!-- << creating-timepicker-html -->
    </StackLayout>

    <StackLayout row="1" class="hour" *ngFor="let hour of hours">
        <Label [text]='hour.hour'></Label>
        <Label [text]='hour.minute'></Label>
    </StackLayout>
</Gridlayout>

ts 是:

import { Component, OnInit, ViewChild, ElementRef} from "@angular/core";
import { UserService} from "../../../services/user.service";
import { TimePicker } from "ui/time-picker";
import { HoursModel } from "../../../models/hours.model";

@Component({
  selector: "hours",
  templateUrl:"components/profile/hours/hours.component.html",
  styleUrls:["components/profile/hours/hours.component.css"]
})

export class HoursComponent implements OnInit{

    @ViewChild("timePicker") tp: ElementRef;

    public hours:Array<HoursModel>=[];
    public index:number=0;

    constructor(){}

    ngOnInit(){}

    configure(timePicker: TimePicker) {
        timePicker.hour = 21;
        timePicker.minute = 0;  
    }

    onTap() {
        let time =this.tp.nativeElement;
        this.hours.push(<HoursModel>{id:this.index,hour:time.hour,minute:time.minute});
        console.log(JSON.stringify(this.hours));
        this.index++;
    }

}

【问题讨论】:

    标签: css arrays angular nativescript ngfor


    【解决方案1】:

    你尝试过使用 ObservableArray 吗? https://docs.nativescript.org/cookbook/data/observable-array

    你也可以试试 ChangeDetectorRef detectCahnges() 方法

    【讨论】:

      【解决方案2】:

      您似乎想在列表中显示数据。 尝试使用此代码:

      <ListView [items]="hours | async" >
      <ng-template let-item="hour" >
      <StackLayout>
      <Label [text]='hour.hour'></Label>
      <Label [text]='hour.minute'></Label>
      </StackLayout>
      </ng-template> 
      </ListView>
      

      使用您当前的代码,您不断地将数据相互叠加,因为父组件就是页面本身。 列表视图是您搜索的 UI 元素。

      【讨论】:

      • 感谢您的信息。所以我已经更换了代码,它仍然无法正常工作。甚至当我点击完成时,它会将元素添加到数组中,它不显示值,时间选择器和点击事件不起作用。
      • 对不起,我弄错了。只需更新代码,更多信息请访问docs.nativescript.org/angular/ui/list-view.html
      • 我应该编辑 .ts 文件吗?因为它仍然不起作用
      • 使用 observables 你必须使用异步管道:[items]="hours | async",因为每次发生变化时代码都必须更新。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-05
      • 1970-01-01
      • 2017-01-08
      • 2018-04-01
      相关资源
      最近更新 更多