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?

1

3 Answers 3

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>
Sign up to request clarification or add additional context in comments.

Comments

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....
    }
}

Comments

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)">

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.