NgModel only signs triggers when the actual text field changes in angular2

I have this code below. Basically this is a component with a directive that subscribes to a text field model.

If I type a text field, the subscription triggers and the console log change, however, if the model is changed externally and retrieved from @Input in the component, the subscription in the text field does not start, although the text in the text field is updated.

Why doesn't it start every time the text changes?

  @Directive({
      selector: 'textarea[mydir]',
      host: {'ngFormControl':'myCtrl'}
  })
  class MyDirective {
    myCtrl: any;
    constructor(){
            this.myCtrl = new Control();
            this.myCtrl.valueChanges.subscribe(
            (data) => {
               console.log('Model change', data);
            });
    }
  }




  // Project card
  @Component({
    selector: 'four',
    providers: [],
    styles: [ require('./four.scss') ],
    directives: [NgFor, MyDirective],
    template: `
        Hello, this is working! <br>
        <textarea mydir [(ngModel)]="pp.status"></textarea>
    `,
  })
  export class Four {
    @Input() pp: Array<any>;
    constructor() {
    }

  }
+4
source share
1 answer

. , NgModel update (. https://github.com/angular/angular/blob/master/modules/angular2/src/common/forms/directives/ng_model.ts#L97 ) :

viewToModelUpdate(newValue: any): void {
  this.viewModel = newValue;
  ObservableWrapper.callEmit(this.update, newValue);
}

:

@Component({
  selector: 'four',
  directives: [MyDirective],
  template: `
    Hello, this is working! <br>
    <textarea mydir [(ngModel)]="pp.status" [ngFormControl]="myCtrl"></textarea>
  `,
})
export class Four {
  @Input() pp;

  constructor() {
    this.myCtrl = new Control();
    this.myCtrl.valueChanges.subscribe(
      (data) => {
        console.log('Model change');
      });
  }
}

plunkr: https://plnkr.co/edit/5E4JZhm32bu8rrPV9nEf?p=preview.

Edit

, , , NgModel, valueChanges. , , :

@Directive({
  selector: 'textarea[mydir]',
})
class MyDirective {
  constructor(@Optional() public model: NgModel){
    this.model.control.valueChanges.subscribe(data => {
      console.log('value updated - new value = '+data);
    });
  }
}

plunkr: https://plnkr.co/edit/5E4JZhm32bu8rrPV9nEf?p=preview.

+3

Source: https://habr.com/ru/post/1627626/


All Articles