Skip to content Skip to sidebar Skip to footer

Observable Of Component Attribute Changes In Angular2

When creating a component in angular 2 that has inputs attributes via @Input, how can I get an observable from the changes made to that attribute @Input (not to be confused with us

Solution 1:

I found out the that BehaviorSubject class enables this scenario the best. Instead of creating a separate backend field, you can use the BehaviorSubject's getValue function to peak at the current value. Then use the backing BehaviorSubject to view as an observable for changes.

export classExampleComponent{
    private _userObject: BehaviorSubject<User> = new BehaviorSubject<User>(null);

    @Input()set userObject(value: User): { this._userObject.next(value); }
    get userObject(): User { returnthis._userObject.getValue(); }
}

Solution 2:

Try usings a get and a set, valueChanges() below will fire on being set.

private _userObject: User;
  @Input()set userObject(userObject: User) {
    this._userObject = userObject;
    this.valueChanges();
  }
  get userObject(): User {
    returnthis._userObject;
  }

With an Observable:

private userObjectChange = new Subject<User>();
  userObjectChange$ = this.userObjectChange.asObservable();

  private _userObject: User;
  @Input()set userObject(userObject: User) {
    this.userObjectChange.next(userObject);
    this._userObject = userObject;
  }
  get userObject(): User {
    returnthis._userObject;
  }

To subscribe:

this.newQuote.subscribe(user => {...})

Solution 3:

You can use subject for this:

exportclassExampleComponent {
    @Input() setuserObject(userObject: User) {
       this.userObject$.next(userObject);
    }

    private userObject$ = newSubject<User>();

    constructor():{
        this.userObject$.subscribe(x=>{ this.doStuff() });
    }
}

Solution 4:

The best way to check the change of an input is actually by using the ngOnChanges life cycle.

ngOnChanges(changes: { [propertyName: string]: SimpleChange }) {
  const changedInputs = Object.keys(changes);
  // Only update the userObject if the inputs changed, to avoid unnecessary DOM operations.if (changedInputs.indexOf('userObject') != -1) {
  // do something
  }    
}

Reference: https://github.com/angular/material2/blob/master/src/lib/icon/icon.ts#L143

Post a Comment for "Observable Of Component Attribute Changes In Angular2"