user3261212
user3261212

Reputation: 439

How to execute a function in child component when (change) on a select in the parent component happens

I have child component with a function that I want to call once the (change) event gets triggered on a select in the parent component. Is this possible?

Upvotes: 2

Views: 1540

Answers (2)

Christian Vincenzo Traina
Christian Vincenzo Traina

Reputation: 10444

I wouldn't advise the @AdritaSharma solution since it's not reusable. It requires some boilerplate for every implementation.

I use to adopt this solution:

In parent component:

// HTML:
<select (change)="onChange($event.target.value)">
  <option>...</option>
</select>
<child-component [value]="value"></child-component>

// TS:
value: string;

onChange(value: string) {
  this.value = value;
}

In child component:

_value: string;
@Input() 
set value(v) {
  this._value = v;
  // execute your update code
}
get value() {
  return this._value;
}

Upvotes: 3

Adrita Sharma
Adrita Sharma

Reputation: 22213

Yes, you can use @ViewChild

Try this:

Parent Component:

HTML:

<select (change)="selectDropdownChange()">
    <option >...</option>
</select>

<child-comp #childRef></child-comp>

TS:

@ViewChild('childRef') childRef: ChildComp;

selectDropdownChange() {
    this.childRef.childFunction();
}

Upvotes: 3

Related Questions