Cannot access Inputs from my controller/constructor

前端 未结 1 624
Happy的楠姐
Happy的楠姐 2020-12-01 13:45

I have a simple Angular 2 component with @Input, which I bind to the template. The template shows input data, but I cannot access it from the constructor:

1条回答
  •  离开以前
    2020-12-01 14:22

    Because the Input property isn't initialized until view is set up. According to the docs, you can access your data in ngOnInit method.

    import {Component, bootstrap, Input, OnInit} from '@angular/core';
    import DataService from './data-service';
    
    @Component({
        selector: 'app-cmp',
        template: `{{data.firstName}} {{data.lastName}} {{name}}`
    })
    export default class NamesComponent implements OnInit {
      @Input() data;
      name: string;
      constructor(dataService: DataService) {
        this.name = dataService.concatNames("a", "b");
        console.log(this.data); // undefined here
      }
      ngOnInit() {
        console.log(this.data); // object here
      }
    }
    

    0 讨论(0)
提交回复
热议问题