无法获取输入属性值 - Angular

时间:2018-04-19 13:32:33

标签: angular input components

todo.component.ts

import { Component, OnInit } from '@angular/core';
import{ TaskService } from './../task.service';
@Component({
  selector: 'app-todo',
  templateUrl: './todo.component.html',
  styleUrls: ['./todo.component.css']
})
export class TodoComponent implements OnInit {
  chosenstatus="todo";
  todoService:TaskService;
  constructor(toDoS:TaskService) { 
    this.todoService=toDoS;
  }

  ngOnInit() {
  }

}

todo.component.html

<app-task [sts]="chosenstatus"></app-task>   

task.component.ts

import { Component, OnInit, Input } from '@angular/core';
import { TaskService } from './../task.service';
@Component({
  selector: 'app-task',
  templateUrl: './task.component.html',
  styleUrls: ['./task.component.css']
})
export class TaskComponent implements OnInit {
@Input() sts;
  todoService;
  constructor(toDoS:TaskService) { console.log(this.sts) /*here it shows undefined*/
    this.todoService=toDoS.getTasklist(this.sts);
  }

  ngOnInit() {
  }

}

task.service.ts

export class TaskService {
   tasklist= [{taskname:"sample task",taskdetail:"This is a test task",status:"todo"}];
   filteredtask;
  constructor() { }
  getTasklist(chosenstatus){
    return this.tasklist.filter((e)=>{
      console.log('ngf'+chosenstatus); /*here it shows undefined*/
        if(e.status==chosenstatus){

          return e;

        }
    });

  }

  addTask(name,task){
    this.tasklist.push({taskname:name,taskdetail:task,status:'todo'});
  }



}

我通过Input属性将变量(chosenstatus)从todo组件传递给任务组件,但它没有得到send.It显示未定义。请告诉我我在做什么错误。

2 个答案:

答案 0 :(得分:0)

在您的任务组件中,而不是构造函数,请尝试:

ngAfterViewInit() {
    this.todoService=toDoS.getTasklist(this.sts);
}

答案 1 :(得分:0)

使用ngOnInit而不是构造函数。

ngOnInit() { 
    console.log(this.sts) ;
    this.todoService=toDoS.getTasklist(this.sts);
  }