如何将@Input 定义为FormControl?
How to define @Input as FormControl?
我有以下组件:
@Component({
selector: "form-component",
template: ``
})
export class FormComponent {
@Input() userInput?: string;
}
现在我想将成员 userInput
(我总是将输入绑定设为可选,因为它们可能不会被使用)转换为 FormControl
,方法是编写:
@Input() userInput = new FormControl("");
或者这与绑定机制有任何冲突吗?
关于类型,这似乎不是一个好的做法,因为 userInput
不再是 string
。
我的问题
如何 属性 将 @Input
绑定分配给 FormControl
?
建议
可能有必要像这样在 onInit 中分配(可能)绑定值:
@Component({
selector: "form-component",
template: ``
})
export class FormComponent implements OnInit{
@Input() userInput?: string;
userControl: FormControl;
ngOnInit() {
this.userControl = new FormControl(this.userInput ? this.userInput : "");
}
}
我假设输入类型是字符串。所以我会像你在你的建议中所做的那样绑定它。但我会在 change 而不是 onInit 上做。
ngOnChanges() {
this.userControl = new FormControl(this.userInput ? this.userInput : "");
}
我想不通您为什么要在其他地方创建 FormControl 并将其作为输入传递。
最简单的方法:
@Component({
selector: "form-component",
template: ``
})
export class FormComponent {
@Input()
set userInput(v: string){
this.userControl.setValue(v || "");
}
userControl: FormControl = new FormControl("");
}
根据您打算如何使用此组件,实施 ControlValueAccessor
接口可能会更好。
我有以下组件:
@Component({
selector: "form-component",
template: ``
})
export class FormComponent {
@Input() userInput?: string;
}
现在我想将成员 userInput
(我总是将输入绑定设为可选,因为它们可能不会被使用)转换为 FormControl
,方法是编写:
@Input() userInput = new FormControl("");
或者这与绑定机制有任何冲突吗?
关于类型,这似乎不是一个好的做法,因为 userInput
不再是 string
。
我的问题
如何 属性 将 @Input
绑定分配给 FormControl
?
建议
可能有必要像这样在 onInit 中分配(可能)绑定值:
@Component({
selector: "form-component",
template: ``
})
export class FormComponent implements OnInit{
@Input() userInput?: string;
userControl: FormControl;
ngOnInit() {
this.userControl = new FormControl(this.userInput ? this.userInput : "");
}
}
我假设输入类型是字符串。所以我会像你在你的建议中所做的那样绑定它。但我会在 change 而不是 onInit 上做。
ngOnChanges() {
this.userControl = new FormControl(this.userInput ? this.userInput : "");
}
我想不通您为什么要在其他地方创建 FormControl 并将其作为输入传递。
最简单的方法:
@Component({
selector: "form-component",
template: ``
})
export class FormComponent {
@Input()
set userInput(v: string){
this.userControl.setValue(v || "");
}
userControl: FormControl = new FormControl("");
}
根据您打算如何使用此组件,实施 ControlValueAccessor
接口可能会更好。