首页 文章

如何在Angular 4中将组件声明为FormControl?

提问于
浏览
2

我试图将组件声明为Form Control .

<my-child-component formControlName="selectedSeats"></my-child-component>

Based on this answer我尝试使用ControlValueAccessor这样的事情,

public propagateChange: any = () => {};
public validateFn: any = () => {};

get selectedClasses() {

    return this.myForm.get('selectedSeats').value;
}
set selectedClasses(val) {
    this.propagateChange(val);
}
public ngOnChanges(inputs) {

}
public writeValue(value) {

}
public registerOnChange(fn) {
    this.propagateChange = fn;
}
public registerOnTouched(fn) {
}

public validate(c: FormControl) {
    return this.validateFn(c);
}

我试图将 this.myForm.get('selectedSeats').value 的值作为组件值传递并尝试绑定到formcontrolname . 但是这段代码不起作用,也没有抛出错误 .

有人可以请告诉我如何将 this.myForm.get('selectedSeats').value 值设置为my-child-component值并传递给formcontrol?

父组件是动态反应嵌套表单 . 在父表单中我调用另一个子组件,它有自己的一组表单,它将返回一个值,它将存储在selectedSeats输入字段中 . 所以现在我需要将该字段值传递给parent并使用formcontrol在父嵌套表单上绑定 .

1 回答

  • 0

    您应该使用formControl对象而不是formControlName . 在组件中创建输入并获取对象 . 您的代码将如下所示:

    export class MyChildComponent {
      @Input() formControlObject: FormControl;
    
      getControlValue(){
        return this.formControlObject.value;
      }
    }
    

    现在,您将对象传递给此组件,如下所示:

    <my-child-component [formControlObject]="myForm.controls['selectedSeats']"></my-child-component>
    

    希望它会有所帮助

相关问题