Search code examples
angularangular2-components

How to programatically change the input value of a component which was already rendered (Angular 2)


In my Angular 2 app I have a component (mainComp) which includes another one via

 <my-comp></my-comp>

my-comp emits (on select / click) it's value (it's a custom dropdown) via

this.optionSelected.emit(currentOption == "Not described" ? null : currentOption);

mainComp receives the value of the dropdown by


Solution

  • You've got a 2-way-binding, so if the object changes, the result should also be refreshed. If you've got an EventEmitter, subscribe in the constructor like:

    class MainComp {
      let value;
      ...
      constructor(private myComp : MyComp) {
        myComp.optionSelected.subscribe{
          (value) => this. value = value;
        }
    }
    

    Now, everytime the EventEmitter fires emit, the value-attribute in MainComp will be updated.

    If you want to something facy, take a look at ngOnChanges (https://angular.io/docs/ts/latest/cookbook/component-communication.html)

    Update: Do you mean sth. like this:

    class MainComp {
      template: `<myComp [(value)]=value></myComp>`
      ...
    }
    
    class MyComp {
      @Input(): value;
      ...
    }
    

    This should create a 2-way-binding, so if one of the Components edits value, the other gets notified. Take a look at this: https://angular.io/docs/ts/latest/guide/template-syntax.html#!#ngModel