Bouazza
Bouazza

Reputation: 139

use an input in class on angular2 with typescript

I am trying to use an input that i sent by appcomponent to my select component.

I need to use the value in my class. The problem that it hasn't been identified on my class but when i put it in the template i can see it.

For example in this component:

import {Component, Input} from 'angular2/core';
@Component({
selector: 'test',
template: "<h4>test 1 {{test_input}}</h4>   <br>" 
})
export class TestComponent {
private test_test;

@Input() test_input: string;
}

I need to use test_input for example to modify it.

Upvotes: 2

Views: 3170

Answers (4)

Bouazza
Bouazza

Reputation: 139

this is my ngselect component

@Component({
selector: 'select-test',
template: `<ng-select [allow-clear]="true"
            [items]="items"
            [disabled]="disabled"
            (data)="refreshValue($event)"
            (selected)="selected($event)"
            (removed)="removed($event)"
            (typed)="typed($event)"
            [placeholder]="'No city selected'"></ng-select> {{dslam}}`,
directives: [Select, NgClass, CORE_DIRECTIVES, FORM_DIRECTIVES, ButtonCheckbox]
})
export class SelectComponent {
private value: any = {};
//private items:Array<string> = [];
@Output() selected_value = new EventEmitter();
@Input() dslam: any;
private _disabledV:string = '0';
private disabled:boolean = false;
private items: Array<string> = [];
constructor(){
  this.items = this.dslam;
}

so what i need is to put my input "dslam" which is an array into "items" everytime i change it with my typeahead (which i have the input dslam) the problem that when i change it i can see that it changes but i didn't find the solution to change my array on my select i hope i was clear

Upvotes: 1

Mark Rajcok
Mark Rajcok

Reputation: 364697

i need to use test_input for example to modify it

If you need to modify the value whenever a value change is propagated to the TestComponent, use a setter:

@Input() set test_input(newValue: string) { ... }

This is discussed in the Component Interaction cookbook, the Intercept input property changes with a setter example.

Upvotes: 1

micronyks
micronyks

Reputation: 55443

You can even check current and previous value of test_testvariable.

export class TestComponent {

  @Input() test_test:string;

  ngOnChanges(...args: any[]) {
        console.log('onChange fired');
        console.log(args[0].test_test.currentValue);
        console.log(args[0].test_test.previousValue)
  }

  ngOnInit() {
    console.log(this.test_input);
  }
}

Upvotes: 1

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657338

The input isn't set before ngOnInit() is called. Move your code to this method

export class TestComponent {
  private test_test;

  @Input() test_input: string;

  ngOnInit() {
    console.log(this.test_input);
  }
}

and it will do what you expect.

Upvotes: 2

Related Questions