要获取Angular自定义表单控件的默认值,可以使用ngOnInit
生命周期钩子函数来设置默认值。
以下是一个示例代码:
CustomFormControlComponent
:import { Component, forwardRef, OnInit } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
@Component({
selector: 'app-custom-form-control',
template: `
`,
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CustomFormControlComponent),
multi: true
}
]
})
export class CustomFormControlComponent implements ControlValueAccessor, OnInit {
value: string;
ngOnInit() {
this.value = 'Default Value'; // 设置默认值
}
// 实现ControlValueAccessor接口的方法
writeValue(value: any) {
this.value = value;
}
registerOnChange(fn: any) {
// 注册onChange回调函数
}
registerOnTouched(fn: any) {
// 注册onTouch回调函数
}
}
import { Component } from '@angular/core';
@Component({
selector: 'app-parent-component',
template: `
`
})
export class ParentComponent {
customValue: string;
ngOnInit() {
this.customValue = 'Default Value'; // 获取默认值
}
}
在上述代码中,通过在ngOnInit
方法中设置CustomFormControlComponent
的value
属性来设置默认值。在父组件中,通过在ngOnInit
方法中设置customValue
属性来获取默认值。
上一篇:Angular 转换后日期改变