自定义组件中的ngModel只以单向工作

时间:2016-03-25 15:43:32

标签: javascript angular

假设我有一个组件

const DEFAULT_VALUE_ACCESSOR = CONST_EXPR(new Provider(
NG_VALUE_ACCESSOR, {useExisting: forwardRef(() => MyComp), multi: true}));

@Component({
 selector: 'my-comp',
  template: `
     <another-one></another-one>  
  `,
  providers: [DEFAULT_VALUE_ACCESSOR]

现在我使用的组件如下:

@Component({
 selector: 'app',
 template: `<my-comp [(ngModel)]="someValue"></my-comp>
         <input [(ngModel)]="someValue" />`
})
class App {
   someValue: number = 5 
}

该值将传递给<my-comp>组件,但在此之后,当输入中的值发生更改时,ngModel会更新,但不会更新<my-comp>。还有其他我需要配置的东西吗?

2 个答案:

答案 0 :(得分:2)

实际上,您需要显式调用Angular2注册的onChange回调:

@Component({
  (...)
})
export class MyComp implements ControlValueAccessor {
  onChange = (_) => {};
  onTouched = () => {};

  writeValue(value: any): void {
    (...)
  }

  registerOnChange(fn: (_: any) => void): void { this.onChange = fn; }
  registerOnTouched(fn: () => void): void { this.onTouched = fn; }
}

例如,当您考虑此自定义组件的状态发生更改时。以下是点击示例:

@Component({
  (...)
  template: `
    <div (click)="updateState()">Update state</div>
  `
})
export class MyComp implements ControlValueAccessor {

  writeValue(value: any): void {
    this.internalState = value;
  }

  updateState() {
    this.internalState = 'new state';
    this.onChange(this.internalState);
  }
}

本文可以为您提供更多提示(请参阅“与NgModel兼容的组件”部分):

答案 1 :(得分:0)

ngOnChanges()的值发生变化时,会调用

@Input()

@Component({
 selector: 'my-comp',
  template: `
     <another-one></another-one>  
  `
})
class MyComp {
  @Input() someField:number;

  ngOnChanges(changes) {
    console.log(changes);
  }
}

现在我使用的组件如下:

@Component({
 selector: 'app',
 template: `<my-comp [someField]="someValue"></my-comp>
         <input [(ngModel)]="someValue" />`
})
class App {
   someValue: number = 5 
}