gpt4 book ai didi

javascript - 如何在 Angular 5中使用ngoninit在前端设置日期值

转载 作者:行者123 更新时间:2023-11-30 07:20:32 25 4
gpt4 key购买 nike

我有一个 <input type="date">我想在用户进入路线时填写。通过访问该站点,输入字段应该已经是实际日期。所以我觉得ngOnInit()应该是我需要的。但是,当用户输入路线时,我需要做什么才能将实际日期作为值填充到输入字段中?

我已经尝试通过搜索网络来实现这一点,但只找到了一些针对 angularjs 的旧解决方案,尽管我使用的是 angular 5,它无法与 angularjs 进行比较。我发现的帖子都指向不再存在的范围。

ngOnInit 的文档也对我没有帮助:/

HTML

<div class="form-group">
<label>Eingangsdatum</label>
<input type="date" [(ngModel)]="dateArrival" id="dateArrivalPicker" value="" name="dateArrival" class="form-control">
</div>

内容

@Component({
selector: 'app-terminals-create',
templateUrl: './terminals-create.component.html',
styleUrls: ['./terminals-create.component.css']
})
export class TerminalsCreateComponent implements OnInit {

type: String;
serial: String;
layout: String;
dateArrival: Date;
activated: Boolean;
setup: String;
firmware: String;
installedAt: String;
createdBy: String;
createdDate: Date;
lastModified: Date;
lastModifiedBy: String;
notes: String;
macAddress: String;


constructor(
private validateService: ValidateService,
private flashMessage: FlashMessagesService,
private authService: AuthService,
private router: Router
) { }

ngOnInit() {}

}

如果我确实喜欢 briosheje 在他的评论中写的,那么他的回答不会:/。还有一件事......通过使用他的评论,我在控制台中发现了两个大错误:

Error: If ngModel is used within a form tag, either the name attribute must be set or the form
control must be defined as 'standalone' in ngModelOptions.

Example 1: <input [(ngModel)]="person.firstName" name="first">
Example 2: <input [(ngModel)]="person.firstName" [ngModelOptions]="{standalone: true}">

如果我现在给我的 <input type="date" [ngModel]="todaysDate | date:'dd-MM-yyyy'" (ngModelChange)="todaysDate = $event" [value]="todaysDate | date:'yyyy-MM-dd'"> 起个名字用实际日期填充此字段的功能消失了,只有 TT.MM.YYYY 站在那里。我能做什么?

最佳答案

应该足够添加:

ngOnInit() {
this.dateArrival = new Date();
}

并更改您的 HTML,以便它自己处理日期到字符串,反之亦然,就像这个 plunker 中建议的那样(取自另一个 SO 帖子):plnkr.co/edit/s5OMg2olU2yHI246nJOG?p=preview

<input type="date" [ngModel] ="dateArrival | date:'yyyy-MM-dd'" (ngModelChange)="dateArrival = $event">

ngModelChange 将自动触发更改并将处理日期转换。 NgModel 将直接通过 date pipe 显示日期

关于javascript - 如何在 Angular 5中使用ngoninit在前端设置日期值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47677591/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com