T Lee
T Lee

Reputation: 35

@Input and @Output are always undefined in Angular-Cli

Whatever values are inside the individuals are printed without issues but whatever is obtained using @Input or @Output is not displayed.

child.component.ts

@Component({
  selector: 'app-form-input',
  templateUrl: './form-input.component.html',
  styleUrls: ['./form-input.component.scss']
})

export class FormInputComponent implements OnInit {
    @Input() fieldType: string;
    //with another Input and 1 Output DOM

 constructor(
    ) {
    }

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

parent.component.html

<app-form-input (value)="action($event)"
    [fieldType]="date"
    [maxAllowItem]="1">
</app-form-input>

Is there anything goes wrong in syntax? The Log always show 'undefined' in all cases.

Thanks

Upvotes: 1

Views: 1503

Answers (2)

dev-dan
dev-dan

Reputation: 6283

I think this is trying to pull in a variable defined within your component.

Try the following syntax, wrap the string again, this should ensure you are passing a string and not a variable from the component, the input will then know to expect a string.

[fieldType]="'date'"

This is wrapping the string in " and '.

Upvotes: 2

asimhashmi
asimhashmi

Reputation: 4378

You may need to initialize the initial values of your @Input and @Output variables inside your component because @Input properties will be undefined unless they are provided from outside and @Output properties need to be initialized with EventEmitter

Also you need to check the values inside ngOnChanges which will be executed during Change Detection

Your code will be like this:

@Component({
  selector: 'app-form-input',
  templateUrl: './form-input.component.html',
  styleUrls: ['./form-input.component.scss']
})

export class FormInputComponent implements OnInit {
    @Input() fieldType: string;
    @Output() event: EventEmitter<any>
    //with another Input and 1 Output DOM

    constructor() {
       this.fieldType = ''
       this.event = new EventEmitter()
    }
    ngOnInit() {

    }
    ngOnChanges() { // <- it will run every time and give you the latest value of fieldType
      console.log(this.fieldType);
    }
}

Upvotes: 0

Related Questions