2017-02-17 124 views
0

将路由器参数(id)传递给ngForm然后传递给事件发送器只有一点困难。这里是我如何获得id - 正如你所看到的第一个console.log工作正常,我可以从路由器获取id。现在,我想这个分配给我的singleOpenHome对象(但得到一个未定义的错误):Angular2 - 将路由器参数作为变量传递给ngForm

@Input() singleOpenHome: OpenHomeModel; 

ngOnInit() { 
     // Get the slug on it from the router 
     this.route.params.forEach((params: Params) => { 
      let id = params['propertyID']; 
      console.log('id on the child is:'+id); 
      //this.singleOpenHome.propertyID == id; Cannot read property 'propertyID' of undefined 
     }); 
    } 

现在我想这个传递给形式:

<form class="my2" #form="ngForm" (ngSubmit)="handleSubmit(form.value, form.valid)" novalidate></form> 

这里是我的事件emmitter:

@Output() 
    update: EventEmitter<OpenHomeModel> = new EventEmitter<OpenHomeModel>(); 

    constructor(private route: ActivatedRoute) {} 

    handleSubmit(sinlgeOpenHome: OpenHomeModel, isValid: boolean) { 
     if (isValid) { 
      this.update.emit(sinlgeOpenHome); 
     } 
    } 

任何帮助表示赞赏

+0

您显示的所有代码是否属于同一个组件?如果是,只需将路由参数分配给类属性 - this.id = params ['propertyID']; - 然后您可以从组件或其模板中的任何位置访问该属性。 – AngularChef

+0

试过这个:this.singleOpenHome.propertyID = params ['propertyID'];但我不能显示像{{singleOpenHome.propertyID}}模板不会工作的值。 – rhysclay

+0

我不明白。你为什么不尝试我建议的代码?你显示的所有代码是否属于同一个组件? – AngularChef

回答

1

我所遇到的问题具体涉及到转换route.paramsObservable变成Promise这是forEach所做的。考虑简单地使用subscribe

ngOnInit() { 
    // Get the slug on it from the router 
    this.route.params.subscribe(params => { 
    const id = params['propertyID']; 
    console.log(`id on the child is: ${id}`); 
    }); 
} 

这看起来像行一个错字

this.singleOpenHome.propertyID == id; 

你进行比较,而不是分配。

这就是说你可能有其他的错误导致该属性未定义。由于它被标记为输入,我假定它来自外部绑定。确保您传递给此绑定的值已正确初始化。

+0

你是如此正确 - 我没有正确地完成绑定,我有一个父容器,它应该初始化singleOpenHome对象并将它传递给它的子组件,那么我可以分配propertyID变量(但我会通过绑定从父项传入) – rhysclay

相关问题