Search code examples
angulartypescriptrxjsobservablestring-interpolation

Can we concatenate string and observable value and pass as input parameter


I have a child component which expecting a string input parameter from its parent. From the parent I want to pass an observable along with additional string data. How can we do this without setting value from component.ts ? Need to do something like this in component.html <Child [inputparam] = " something {{obs$|async}} something more "> Thank you


Solution

  • It is exactly as you describe it.

    Define in your Parent Component an Observable and a string

    myObservable: BehaviorSubject<string> = new BehaviorSubject<string>('');
    myString = '';
    

    Pass it to your Child Component

    <child-component [myObservable]="myObservable" [myString]="myString"></child-component>
    

    And in your Child Component you wait for those values to be passed.

    @Input() myObservable: BehaviorSubject<string> = new BehaviorSubject<string>('');
    @Input() myString = '';
    

    That's actually it.

    The observable works among both components now.

    Variant 2 :: grouped

    When you want to put it all in one you have to define an object.

    class AllTogether {
        myObservable: BehaviorSubject<string>;
        myString: string;
    }
    

    Instantiate it in your parent component

    allTogether = new AllTogether();
    allTogether.myObservable = new BehaviorSubject<string>('');
    allTogether.myString = '';
    

    Pass it to your Child Component

    <child-component [allTogether]="allTogether"></child-component>
    

    And in your Child Component you wait for the object to be passed.

    class AllTogether {
        myObservable: BehaviorSubject<string>;
        myString: string;
    }
    
    @Input() allTogether = new AllTogether();
    

    And then access the values

    this.allTogether.myObservable.subscribe( /* do something */)