Nick
Nick

Reputation: 10163

How to transform input data inside custom component?

For example, I have component:

@Component({
  selector: 'my-selector',
  inputs: ['data'],
  moduleId: module.id,
  template: '<p>{{transformedData}}</p>'
})
export class MyComponent {
  public transformedData: string;
  @Input() public data: string;

  // How to call this event on "data" change?
  public someEvent() {
    this.transformedData = this.data + '!';
  }
}

How to call someEvent() on data changes?

Upvotes: 4

Views: 1715

Answers (1)

micronyks
micronyks

Reputation: 55443

onchanges will get fired when data is changed.So, within onChanges you can call someEvent function.

export class MyComponent {
  public transformedData: string;
  @Input() public data: string;

  ___________________________________________________________________________________________
  // EDIT: you can also do it. Not necessary but can be done this way too.
 //  Note: If you go with this approach, you don't need to use onchanges hook and don't require above @Input public data line.
    @Input() set data(data:string)
           console.log(data);
           this.someEvent();
   }
 ____________________________________________________________________________________________ 


  ngOnChanges(...args: any[]) {

        console.log(args);
        this.someEvent();
  }

  // How to call this event on "data" change?
  public someEvent() {
    this.transformedData = this.data + '!';
  }
}

Upvotes: 3

Related Questions