【问题标题】:Angular2 - Pass router param as variable to ngFormAngular2 - 将路由器参数作为变量传递给 ngForm
【发布时间】:2017-07-06 20:05:50
【问题描述】:

将路由器参数 (id) 传递给 ngForm 然后传递给事件发射器有点困难。这是我获取 id 的方式 - 正如您所看到的第一个 console.log 工作正常,我可以从路由器获取 id。现在我试图将它分配给我的 singleOpenHome 对象(但得到一个未定义的错误):

@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>

这是我的事件发射器:

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

    constructor(private route: ActivatedRoute) {}

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

任何帮助表示赞赏

【问题讨论】:

  • 您展示的所有代码是否属于同一个组件?如果是,只需将路由参数分配给类属性 — this.id = params['propertyID']; — 然后您可以从组件或其模板中的任何位置访问该属性。
  • 试过这个:this.singleOpenHome.propertyID = params['propertyID'];但我无法在模板中显示值,例如 {{ singleOpenHome.propertyID }} 不起作用。
  • 我不明白。你为什么不试试我建议的代码?你展示的所有代码都属于同一个组件吗?
  • 是的所有相同的组件。我应该把 this.id... 放在我的 ngOnInit 的什么位置?
  • 是的。 let id = ... 变为 this.id = ...。您还需要在类上声明 id 属性。

标签: angular typescript angular2-template angular2-forms


【解决方案1】:

我遇到了与将 route.params Observable 转换为 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;

您正在执行比较而不是分配。

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

【讨论】:

  • 你说得对——我没有正确完成绑定,我有一个父容器应该初始化 singleOpenHome 对象并将其传递给它的子组件,然后我可以分配 propertyID 变量(但是我将通过来自父母的绑定传递它)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-06
  • 2018-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多