15

我有 ParentComponent 和 ChildComponent,我需要将 ParentComponent 中的 ngModel 传递给 ChildComponent。

// the below is in ParentComponent template
<child-component [(ngModel)]="valueInParentComponent"></child-component>

如何获取 ChildComponent 中 ngModel 的值并对其进行操作?

4

3 回答 3

25

您需要ControlValueAccessor在子类中实现。这就是将您的组件定义为可以使用角度方式绑定的“具有价值”的原因。

在这里阅读更多信息:http: //blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2.html

于 2016-12-27T23:06:03.317 回答
1

对于 Parent -> Child,使用 @Input

对于子 -> 父,使用 @Output

所以要同时使用:

在父组件中

打字稿:

  onValueInParentComponentChanged(value: string) {
    this.valueInParentComponent = value;
  }

html

<child-component 
 (onValueInParentComponentChanged)="onValueInParentComponentChanged($event)"
 [valueInParentComponent]="valueInParentComponent">
</child-component>

在子组件中

打字稿:

export class ChildComponent {  
   @Input() valueInParentComponent: string;
   @Output() onValueInParentComponentChanged = new EventEmitter<boolean>();
} 

onChange(){
  this.onValueInParentComponentChanged.emit(this.valueInParentComponent);
}

html

<input type="text" [(ngModel)]="valueInParentComponent"   
    (ngModelChange)="onChange($event)"/>

完整示例

https://plnkr.co/edit/mc3Jqo3SDDaTueNBSkJN?p=preview

实现此目的的其他方法:

https://angular.io/docs/ts/latest/cookbook/component-communication.html

于 2016-12-27T19:07:21.183 回答
1

听起来您正在尝试包装表单控件。我写了一个库来帮助你做到这一点!s-ng-utils有一个超类可用于您的父组件:WrappedFormControlSuperclass. 你可以像这样使用它:

@Component({
  template: `
    <!-- anything fancy you want in your parent template -->
    <child-component [formControl]="formControl"></child-component>
  `,
  providers: [provideValueAccessor(ParentComponent)],
})
class ParentComponent extends WrappedFormControlSuperclass<ValueType> {
  // This looks unnecessary, but is required for Angular to provide `Injector`
  constructor(injector: Injector) {
    super(injector);
  }
}

正如@Amit 的回答所暗示的那样,这假设<child-component>有一个。ControlValueAccessor如果您正在编写<child-component>自己的代码,那么还有一个超类s-ng-utils可以帮助您:FormControlSuperclass.

于 2019-03-10T18:57:35.837 回答