我自定义了datepicker的返回值,并且我想为此控件设置默认值
FormControl获取值,但输入框未获取值。
此处的在线示例:https://stackblitz.com/edit/angular-update-control-input
mydatepicker.component.ts
import {Component, OnInit, forwardRef, Input, ViewChild} from '@angular/core';
import {ControlValueAccessor, NG_VALIDATORS, NG_VALUE_ACCESSOR} from '@angular/forms';
@Component({
selector: 'app-mydatepicker',
templateUrl: 'mydatepicker.component.html',
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => MydatepickerComponent),
multi: true
},
],
})
export class MydatepickerComponent implements ControlValueAccessor, OnInit {
@Input() placeholder = 'date';
model: any;
private propagateChange = (_: any) => {
};
writeValue(obj: any): void {
if (obj) {
console.log(obj);
}
this.model = obj;
}
registerOnChange(fn: any): void {
this.propagateChange = fn;
console.log(fn);
}
registerOnTouched(fn: any): void {}
ngOnInit() {}
outValue(v: string) {
console.log(v);
this.propagateChange(v.replace(/\//g, '-'));
}
}
mydatepicker.component.html
<mat-form-field>
<input matInput [matDatepicker]="picker" [(ngModel)]="model" (focus)="picker.open()" [placeholder]="placeholder" #ref (dateChange)="outValue(ref.value)">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>
app.component.html
<form [formGroup]='form'>
<app-mydatepicker formControlName='date'></app-mydatepicker>
{{form.value | json}}
</form>
app.component.ts
export class AppComponent implements OnInit {
form: FormGroup;
ngOnInit() {
this.form = new FormGroup({
date: new FormControl(new Date().toLocaleDateString())
});
}
}