2

I need some help with setting variables in class by text input,

nameChange(str){
    this.service.setName(str);
    console.log(str);
}

there is a example class, which modify variable, so how should input looks like, when I want just to modify variable anytime the input changes?

Jędrek Markowski
  • 444
  • 3
  • 6
  • 25
  • If you are looking for more fine-grained control, have a look at this post:https://stackoverflow.com/questions/32051273/angular2-and-debounce – Radu Cojocari Jun 28 '17 at 11:00

3 Answers3

1

You can use two way databinding.

Example:

<input [(ngModel)]="property">

<p>{{property}}</p>

Take a look here.

If you want to call a function like the one in your code, use this:

<input (input)="nameChange($event.target.value)">
AT82
  • 71,416
  • 24
  • 140
  • 167
Spitzbueb
  • 5,233
  • 1
  • 20
  • 38
1

You can intercept input property changes with a setter, try this:

// component:

@Component({
    selector: 'my-component',
    template: '<h3> My component </h3>'
})

export class MyComponent {
    @Input()
    set name(str: string) {
        this.service.setName(str);
        console.log(str);
    }
}

// HTML where component is used:

<my-component [name]="Bombasto"></my-component>
Faly
  • 13,291
  • 2
  • 19
  • 37
1

you have to use ngOnChange Event in this case as below. So whenever your input variable myVar value change it will call ngOnChanges event

@Input() myVar:any;

ngOnChanges(changes: any) {
    if (changes.myVar != null && changes.myVar.currentValue != null) {
       //your logic to update any variable or other....
    }
}