【发布时间】:2026-02-01 09:40:01
【问题描述】:
在 Angular 中,我从 JsonFile 检索时间戳,然后我想在下拉菜单中显示它,但我不知道如何从 ngOnInit() 获取变量以将其传递给我用来提供的变量下拉菜单。我将占位符放在'来自ngOnInit()的时间戳'下面的代码中,这必须是一个字符串。
这是search.component.ts 文件:
times: Timestamp[] = [
{ value: 'timestamp from ngOnInit()', viewValue: 'timestamp from ngOnInit()' },
];
this.Service.getContent().then(results => {
this.data = results;
for (let i = 0; i < this.data.length; i++) {
Object.entries(this.data[i].x_data).map(([key, value]) => {
//timestamp
this.xvalue = this.data[i].timestamp
//converted timestamp to date & time
this.date = moment(this.data[i].timestamp).format('DD-MM-YYYY HH:mm:ss').toLocaleString();
this.strTimestamp = String(this.xvalue)
this.strDate = String(this.date)
return {
timestamp: this.strTimestamp,
date: this.strDate,
}
});
}
})
}
html 文件:
<form>
<mat-form-field appearance="fill">
<mat-label>Select timestamp <mat-icon>access_time</mat-icon></mat-label>
<mat-select [(ngModel)]="selectedValue" name="food">
<mat-option *ngFor="let time of times" [value]="time.value">
{{time.viewValue}}
</mat-option>
</mat-select>
</mat-form-field>
<p> Selected timestamp: {{selectedValue}} </p>
</form>
【问题讨论】:
标签: angular angular-material angular-ngmodel