Mithun S
Mithun S

Reputation: 418

How to do combineLatest operator in valueChanges subscriptions

showDateCriteria = combineLatest(this.myForm.controls['name'].valueChanges, this.myForm.controls['age'].valueChanges, (name, age) => ({name, age}))
.subscribe(val => !(val.name==null ||val.age==null ));

I have tried this code with combineLatest Operator and showDateCriteria

<div *ngIf="{{showDateCriteria | async}}">Show This</div>

I am unable to show the <div> eventhough particular condition is satisfied

https://stackblitz.com/edit/angular-rs3d7a

Upvotes: 0

Views: 1633

Answers (1)

Roberto Zvjerković
Roberto Zvjerković

Reputation: 10147

As the error says ERROR Error: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'.

You're trying to async pipe a subscription, which doesn't make sense.

You should pipe streams.

this.showDateCriteria =
    combineLatest(
        this.myForm.controls['name'].valueChanges,
        this.myForm.controls['age'].valueChanges, (name, age) => ({
            name,
            age
        }));
this.showDateCriteria.subscribe(val => !(val.name == null || val.age == null));

EDIT:

You should also startWith, otherwise the combineLatest will not trigger. Also, the logic was wrong, you should return boolean true when either of them is not null, like so:

this.showDateCriteria = combineLatest(
    this.myForm.controls['name'].valueChanges.pipe(startWith(null)),
    this.myForm.controls['age'].valueChanges.pipe(startWith(null)),
    (name, age) => {
        console.log(name);
        return name || age;
    });

https://stackblitz.com/edit/angular-g6vi6k?file=src%2Fapp%2Fapp.component.ts

Upvotes: 1

Related Questions