HiddenMarkow
HiddenMarkow

Reputation: 613

Detect changes in HTML of child component from parent component in Angular

So I have a parent component say

@Component({
  selector: 'parent-comp'
  template: '<child-comp [inputData]="responseData"></child-comp>
})

export class ChildComponent {

  public responseData: any;

  getData() {
    this.responseData = getDataFromSomeService();
  }

  - - - - -
}

My child component is something like this

@Component({
  selector: 'child-comp'
  templateUrl: 'someUrl'
})

export class ChildComponent {
   @Input
    inputData: any;

   - - - - -
}

My child component html has a select box

<select> 
  <option disabled
    value=""
    selected> Select
  </option>
  <option *ngFor="let val of values"
          [value]="val.key"> {{val.name }}
  </option>
</select>

So every time an "option" is selected in "select" I want to get different data from parent component as an input to child component. That is the "responseData" to be sent as input to child component is different for different "option" selected.

In my scenario parent component is kind of data transformer which sends different data based on the options selected in child component.

So how do I detect that a different "option" in "select" box is selected and send the key attached with "option" to parent component to get different "responseData"

Upvotes: 0

Views: 3239

Answers (1)

Raed Khalaf
Raed Khalaf

Reputation: 2065

in the child component, add the output decorator as follows:

@Component({
  selector: 'child-comp'
  templateUrl: 'someUrl'
})

export class ChildComponent {
   @Input
    inputData: any;

   @Output onSelectChange = new EventEmitter<string>();

   onSelectedOptionChanged($event) {
      // trigger the event to parent.
      this.onSelectChange.emit($event.target.value);
   }
   - - - - -
}

and in the child component template

<select (change)='onSelectedOptionChanged($event)'> 
  <option disabled
    value=""
    selected> Select
  </option>
  <option *ngFor="let val of values"
          [value]="val.key"> {{val.name }}
  </option>
</select>

in parent .ts code

@Component({
  selector: 'parent-comp'
  template: '<child-comp [inputData]="responseData" 
            (onSelectChange)='changeResponseData(data)></child-comp>
})



export class ChildComponent {


  public responseData: any;

  getData() {
    this.responseData = getDataFromSomeService();
  }

  changeResponseData(newDate) {
      console.log('new selected option is', newData);
  }
  - - - - -
}

Upvotes: 1

Related Questions