组件上不存在属性

时间:2017-10-16 15:31:50

标签: angular typescript

我有这个Angular 4组件:

export class MenuComponent {

constructor(private menuService: MenuService) { }


@Input(nodes):any;

   getMenu(path:string): void {
   this.menuService.getData(path).subscribe(data => {
         // Read the result field from the JSON response.

         let newValue = JSON.stringify(data).replace('{"Node":', '[');
         newValue = newValue.substring(0,newValue.length - 1);
         newValue+="]";
        const menu=JSON.parse(newValue);
         this.nodes = menu;
      });

 }
}

我一直收到此错误:Property 'nodes' does not exist on type 'MenuComponent'我不明白为什么,因为nodes属性就在那里。

2 个答案:

答案 0 :(得分:1)

您可以通过两种方式提供输入,

 @Input() hero: Hero;
 @Input('master') masterName: string;

在您的代码中,您提供公共属性名称(bindingPropertyName),但没有可用于组件类的属性,

 @Input(nodes):any;

详细了解@Input here

希望这会有所帮助!!

答案 1 :(得分:0)

我通常以这种方式定义@input变量。

  @Input() nodes: any;

我可以看到两个问题

  1. 从您的组件获取undefined或未获得价值的视图。因此,请确保父组件发送正确的值[nodes]="'this is a value"'

  2. 在角度组件生命周期中,确保nodes的值准时到达。

  3. 你也可以添加ngInit生命周期钩子并设置一个默认值,以防没有收到任何东西

      ngOnInit() {
        this.nodes = this.nodes || '';
      }