如何使输入可观察?

sel*_*lf. 23 angular

我有一个带有一些输入的组件,我希望在它发生变化时得到通知.我目前正在通过实现ngOnChanges和确定哪些输入已更改来工作.但是,我更喜欢将我的输入声明设置为@Input('select-values') selectValues:Observable<any>.这将允许我订阅以更清洁的方式发生的任何新变化.

ngOnInit() {
    this.selectValues.subscribe(() => console.log('yay!'));
}
Run Code Online (Sandbox Code Playgroud)

这个问题是我得到了例外TypeError: this.selectValues.subscribe is not a function.

刚刚发现这也有效 - 组件交互.使用setter拦截输入属性更改.

Gün*_*uer 21

您可以将它们包装在一个表单中并听取更改

this.myForm = fb.group({  
  'sku':  ['', Validators.required]  
});

this.sku = this.myForm.controls['sku'];

this.sku.valueChanges.subscribe(  
  (value: string) => {  
    console.log('sku changed to: ', value);  
  }
);

this.myForm.valueChanges.subscribe(  
  (value: string) => {  
    console.log('form changed to: ', value);  
  }
);
Run Code Online (Sandbox Code Playgroud)

http://blog.ng-book.com/the-ultimate-guide-to-forms-in-angular-2/

要么

@Component({
   ...,
   template: '<input (change)="onChange($event.target.value)">'
})
class MyComponent {
  this.inputChange =new Subject();

  onChange(e) {
    this.inputChange.next(e);
  }
}
Run Code Online (Sandbox Code Playgroud)

另请参阅此问题,请打开https://github.com/angular/angular/issues/4062


Thi*_*ier 15

实际上,不可能直接注册与DOM元素事件相关的可观察对象.您需要直接引用DOM元素,然后使用fromEvent方法Observable.

这是一个示例:

@Component({
  (...)
  template: `
    <input #input />
  `
})
export class SomeComponent {
  @ViewChild('input')
  input:ElementRef;

  ngAfterViewInit() {
    var eventObservable = Observable.fromEvent(
              this.input.nativeElement, 'keyup');
  }
}
Run Code Online (Sandbox Code Playgroud)

这个问题也会引起你的兴趣:

也就是说,您可以利用表单控件在更新输入值时得到通知.valueChanges控件的属性可以作为子组件的输入传递.

@Component({
  (...)
  template: `
    <input [ngFormControl]='ctrl'/>
    <child-component [select-values]="ctrl.valueChanges"></child-component>
  `
})
export class SomeComponent {
  constructor() {
    this.ctrl = new Control();

    this.ctrl.valueChanges.subscribe(...);
  }
}
Run Code Online (Sandbox Code Playgroud)


mne*_*dia 8

如果您只需要观察单个输入,则可以快速执行以下操作:

在组件中:

ngOnInit() {
  this.searchField = new FormControl();
  this.searchField.valueChanges.subscribe(term => {
    console.log('searching for', term);
  });
}
Run Code Online (Sandbox Code Playgroud)

在HTML中:

<input type="search" [formControl]="searchField">
Run Code Online (Sandbox Code Playgroud)

并且可能在ngOnDestroy中取消订阅.

  • 值得注意的是,您不能单独使用 FormControl。您必须将其放入 FormGroup 中。 (3认同)
  • 哦,这就是我要找的东西。为什么这么简单却在其他任何地方都没有提及。谢谢! (2认同)