Angular 4指令如何监听注入服务中属性的更改

时间:2017-07-10 10:53:22

标签: angular rxjs directive

我正在使用Angular 4构建应用程序,我有一个包含以下模板的组件:

<input
    [value]="myService.myValue"
    >

其中myService是注入组件的服务:

@Injectable()
    export class MyService {

    public myValue: string; // I could use an RxJS observable/Subject here
}

我需要添加一个正在侦听myValue更改并更改输入文本颜色的指令(或其他内容)。

我该怎么办?有什么想法吗?

谢谢!

4 个答案:

答案 0 :(得分:1)

创建一个共享服务,这样当myValue发生更改时,您会听到它并应用您想要的任何逻辑。

<强>服务

@Injectable()
export class MyService {
    updateMyValue$: Observable<any>;

    private updateMyValueSubject = new Subject<any>();

    constructor() {
        this.updateMyValue$ = this.updateMyValueSubject.asObservable();
    }

    updateVal(newVal) {
        this.updateMyValueSubject.next(newVal);
    }
}

更改值的组件:

this.myService.updateVal('new value');

侦听价值变化的组件

this.myService.updateMyValue$.subscribe(
        (newVal) => {
              this.inputValue = newVal; // I called `inputValue` to the variable that will contain the value of the input. It should be initialized.
              // Here we can apply our own logic such as change color, hide some DOM elements or whatever we need to do
        }
    );

<强>解释

第一个组件是将新值发送给服务,在我们的案例"new value"中。

第二个组件订阅了此Subject,一旦next()被触发,它就会收到新数据。换句话说,该组件正在监听updateVal()功能,一旦触发它就会收到数据。

这是一种非常可靠且实用的组件间通信方式。

答案 1 :(得分:0)

您可以使用以下

的ngClass或ngStyle
<input [value]="myService.myValue" 
       [ngStyle]="{'color': myService.myValue === 1 ? 'red' : 'blue'}">

ngClass

<input [value]="myService.myValue" 
       [ngClass]="{'color-red': myService.myValue === 1, 'color-blue' : myService.myValue === 2}">

检查此plnkr

https://plnkr.co/edit/2IAxwnXOaWS4TUL7aov0?p=preview

答案 2 :(得分:0)

我找到了解决方案:

<input [myDirective]="myService.parameter" myServiceValue="{{myService.value}}" ... >


@Directive({
  selector: '[myDirective]'
})
export class parameterDirective implements OnInit, OnChanges {
  @Input('myDirective') parameter: parameter;
  @Input() myServiceValue: string;

  constructor(private el: ElementRef, private renderer: Renderer) {
  }

  ngOnInit(): void {
  }

  ngOnChanges(changes: SimpleChanges): void {
    switch (this.parameter) {
      case parameter.EnumValue:
        this.renderer.setElementClass(this.el.nativeElement, "my-class", changes.myServiceValue.currentValue > 100);
        break;
      default:
    }

  }
}

答案 3 :(得分:0)

对于你所谈论的内容来说,一个主题是过度的。一般来说,反应主体应该谨慎使用。

您可以使用简单的get访问者

来完成您想要的任务
export class MyService {
  myValue_: string;
  get myValue() {
    return this.myValue_;
  }
}

如果你想让值向另一个方向流动,你可以添加一个set访问者,尽管最好避免使用它,因为在你的服务类中有一个视图会有点讨厌。