angular2 pass ngModel to a child component

前端 未结 3 1409
再見小時候
再見小時候 2020-12-10 12:47

I have ParentComponent and a ChildComponent, and I need to pass the ngModel in ParentComponent to ChildComponent.

// the below is in ParentComponent template         


        
3条回答
  •  醉梦人生
    2020-12-10 13:33

    It sounds like you are trying to wrap a form control. I wrote a library that helps you do that! s-ng-utils has a superclass to use for your parent component: WrappedFormControlSuperclass. You can use it like this:

    @Component({
      template: `
        
        
      `,
      providers: [provideValueAccessor(ParentComponent)],
    })
    class ParentComponent extends WrappedFormControlSuperclass {
      // This looks unnecessary, but is required for Angular to provide `Injector`
      constructor(injector: Injector) {
        super(injector);
      }
    }
    

    This assumes that has a ControlValueAccessor, as @Amit's answer suggests. If you are writing yourself, there is also a superclass in s-ng-utils to help with that: FormControlSuperclass.

提交回复
热议问题