我用过角材料和反应形式。首先,我要获取系统日期并显示它。但是,当我单击提交时,它给出了空值。以下是HTML和TS部分。
<form [formGroup]="atAdminName" (ngSubmit)="onFormSubmit()">
<div class="row">
<div class="col-md-6">
<label style="font-size: 18px">
From :
</label>
<mat-form-field>
<input matInput [matDatepicker]="picker1" formControlName="date1" [formControl]="date" style="font-size:18px">
<mat-datepicker-toggle matSuffix [for]="picker1"></mat-datepicker-toggle>
<mat-datepicker #picker1></mat-datepicker>
</mat-form-field>
<br>
</div>
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary">Show Report</button>
<button type="button" class="btn btn-default waves-effect">Reset</button>
</div>
</form>
下面是TS
export class AdminNameComponent implements OnInit {
atAdminName = new FormGroup({
date1: new FormControl()
});
get date1() { return this.atAdminName.get('date1'); }
date = new FormControl(new Date());
serializedDate = new FormControl((new Date()).toISOString());
constructor(private fb: FormBuilder, public usr?: UserService) {
this.atAdminName = this.fb.group({
date1: new FormControl('', Validators.required),
})
}
onFormSubmit() {
const userid = this.usr.getUserId();
console.log(this.atAdminName.value);
}
}
答案 0 :(得分:1)
您可以尝试此解决方案
我已经在stackblitz上创建了一个演示
安装时刻-npm install moment --save
import moment from 'moment';
ts文件代码
atAdminName: FormGroup;
constructor(private fb: FormBuilder) {
this.atAdminName = this.fb.group({
date1: new FormControl(new Date(), Validators.required),
})
}
onFormSubmit() {
let newdateValue = moment(this.atAdminName.get('date1').value).format("DD-MM-YYYY");
this.atAdminName.get('date1').setValue(newdateValue);
console.log(this.atAdminName.value);
}
/**
* This method is change date format.
*/
dateFormat(date, controlType: string) {
this.atAdminName.get(controlType).setValue(moment(date).format("DD-MM-YYYY"));
}
html文件代码
<form [formGroup]="atAdminName" (ngSubmit)="onFormSubmit()">
<div class="row">
<div class="col-md-6">
<label style="font-size: 18px">
From :
</label>
<mat-form-field>
<input (dateChange)="dateFormat($event.value,'date1')" matInput [matDatepicker]="picker1" formControlName="date1" style="font-size:18px">
<mat-datepicker-toggle matSuffix [for]="picker1"></mat-datepicker-toggle>
<mat-datepicker #picker1></mat-datepicker>
</mat-form-field>
<br>
</div>
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary">Show Report</button>
<button type="button" class="btn btn-default waves-effect">Reset</button>
</div>
</form>
答案 1 :(得分:0)
请删除:[formControl] =“日期”
atAdminName : FormGroup;
constructor(private fb: FormBuilder) {
this.atAdminName = this.fb.group({
date1: new FormControl(new Date(), Validators.required),
})
}
onFormSubmit() {
let updatedDate =
moment(this.atAdminName.get('date1').value).format("DD-MM-
YYYY");
this.atAdminName.get('date1').setValue(updatedDate);
console.log(this.atAdminName.value);
}