0

次のコンポーネントがあります。

@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 : "");
  }

}
4

2 に答える 2

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 に答える