Angular 2数据绑定不适用于输入装饰器

时间:2016-08-04 22:56:30

标签: angular angular2-template 2-way-object-databinding angular2-inputs

我试图根据输入装饰器更改圆环图的值。我能够初始化值,但不能再进一步改变它。

我使用<input type="number" [(ngModel)]="complete"> 2路数据绑定该值。但它不起作用。我认为它不起作用,因为模板已被调用,我们稍后会更改数据。

有没有解决方案。?

工作代码:http://plnkr.co/edit/hYlFp1BX8ebixQMqAtNj?p=preview

父组件代码:

@Component({
  selector: 'my-app',
  providers: [],
  template: `


    <test-component [complete]="complete"></test-component>
    Completed %:<input type="number" [(ngModel)]="complete">

  `,
  directives: [TestComponent]
})
export class App {
  complete:number=40;
  constructor(){

  }
  test(){
    this.complete=60;
  }
}

1 个答案:

答案 0 :(得分:0)

指令complete收到父组件@Input() complete值变化

您的图表是不更新的图表。每次价值变化时,您都必须重新绘制整个图表。

我的建议:让complete成为Observable<integer>并在每次用户更改complete <input>时推送新值。

相关变化:

@Component({
    ...
    <test-component [complete]="complete"></test-component>
    Completed %:<input type="number" [(ngModel)]="complete">
...
export class App {
  complete:number=40;
  constructor(){

变为:

@Component({
    ...
    <test-component [complete]="completeObs"></test-component>
    Completed %:<input type="number" [(ngModel)]="complete" 
                                               (ngModelChange)="completeObs.next($event)">
...
export class App {
  complete:number=40;
  completeObs:Observable<integer> = new BehaviorSubject<integer>(this.complete);
  constructor(){

您还需要更改指令:

export class TestComponent{
  @Input() complete:Observable<integer>;

  ngAfterViewInit() {
    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");

    var colors=['green','orange'];
    var labels=['Completed','Pending'];

    this.complete.subscribe((complete) => {      // <-- notice it subscribes to the input
      let incomplete:integer = 100 - complete;

See plunker demo here