Yefrid rios mora
Yefrid rios mora

Reputation: 89

stencil change @Prop() detection

How can I detect prop changes in stencil, in angular is something like this:

But I don't know how is in stencil.

import { Component, Input, OnInit } from '@angular/core';

@Component({
  selector: 'my-name',
  template: `
      <h2>First name: {{name}} ({{_name}})</h2>
  `,
})
export class ChildComponent implements OnInit {
  private _name: string;
  constructor() {}

  get name(): string {
    // transform value for display
    return this._name.toUpperCase();
  }

  @Input()
  set name(name: string) {
    console.log('prev value: ', this._name);
    console.log('got name: ', name);
    this._name = name;
  }

  ngOnInit() {
    console.log('on init');
    console.log(this._name);
  }
}

I need to detect properties changes

Upvotes: 5

Views: 6054

Answers (1)

lenilsondc
lenilsondc

Reputation: 9810

You can use the @Watch decorator on a method that will trigger when the property changed.

@Watch('name') 
onNameChanged(newValue: string, oldValue: string) {
  this._name = newValue;
}

Note on @Watch: this decorator only trigger on prop changed, it means the onNameChanged() method won't be called the first time that prop is set. In order to intercept the first set, you have to use the componentWillLoad() hook.

componentWillLoad(){
  this.onNameChanged(this.name);
}

Working example:

import { Component, Prop, Watch } from '@stencil/core';

@Component({
  tag: 'my-name'
})
export class ChildComponent {

  private _name: string;

  @Prop() name: string = '';

  @Watch('name')
  onNameChanged(name: string) {
    console.log('prev value: ', this._name);
    console.log('got name: ', name);
    this._name = name.toUpperCase();
  }

  componentWillLoad(){
    this.onNameChanged(this.name);
  }

  render() {
    return (<h2>First name: {this.name} ({this._name})</h2>);
  }
}

Upvotes: 11

Related Questions