[英]how to set date value in frontend with ngoninit in angular 5
我有一個<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,以便它可以自行處理日期(反之亦然),如該插件(從另一篇SO帖子中摘錄 )中所建議的那樣: plnkr.co/edit/s5OMg2olU2yHI246nJOG?p=preview
<input type="date" [ngModel] ="dateArrival | date:'yyyy-MM-dd'" (ngModelChange)="dateArrival = $event">
您可以在component.ts中創建一個變量,例如:
todaysDate: Date = new Date();
然后在您的模板中:
<input type="text" [value]="todaysDate">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.