0

我有以下组件:

@Component({
  selector: "form-component",
  template: ``
})
export class FormComponent {

  @Input() userInput?: string;

}

现在我想通过编写将成员userInput(我总是使 Input 绑定可选,因为它们可能不会被使用)转换为 a :FormControl

@Input() userInput = new FormControl("");

或者这是否与绑定机制有任何冲突?关于类型,这似乎不是一个好习惯,因为不再userInputstring

我的问题

如何将@Input绑定分配给 a 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 : "");
  }

}
4

2 回答 2

0

我假设输入类型是字符串。所以我会像你在你的建议中所做的那样绑定它。但我会在更改而不是 onInit 时这样做。

 ngOnChanges() {
    this.userControl = new FormControl(this.userInput ? this.userInput : "");
  }

我想不出你为什么要在其他地方创建 FormControl 并将其作为输入传递。

于 2019-06-18T12:24:20.133 回答
0

最简单的方法:

@Component({
  selector: "form-component",
  template: ``
})
export class FormComponent {
  @Input()
  set userInput(v: string){
    this.userControl.setValue(v || "");
  }
  userControl: FormControl = new FormControl("");    
}

根据您计划如何使用此组件,实现该ControlValueAccessor接口可能会更好。

于 2019-06-18T12:27:13.197 回答