在 Angular 中的自定义组件中将初始值设置为 select 4

Set initial value to select within custom component in Angular 4

正如您在这个 plunkr (https://plnkr.co/edit/3EDk5xxSLRolv2t9br84?p=preview) 中看到的那样,我有两个 select:一个在主组件中表现正常,一个在自定义组件中,继承 ngModel 设置。

以下代码将 innerNgModel 链接到组件 ngModel。

ngAfterViewInit() {
  //First set the valueAccessor of the outerNgModel
  this.ngModel.valueAccessor = this.innerNgModel.valueAccessor;

  //Set the innerNgModel to the outerNgModel
  //This will copy all properties like validators, change-events etc.
  this.innerNgModel = this.ngModel;
}

有效,因为名称 属性 由两个 select 更新。

然而,当它第一次加载时,第二个 select 没有 selection。

我想我遗漏了一些东西,一种用初始值初始化 innerNgModel 的方法。

做这样的事情是一种奇怪的情况,但我相信要使其正常工作,他们需要实施另一个生命周期挂钩。 AfterModelSet 或类似的东西:)

无论如何,您可以使用简单的 setTimeoutsetValue:

来解决这个问题
ngAfterViewInit() {
   this.ngModel.valueAccessor = this.innerNgModel.valueAccessor;
   this.innerNgModel = this.ngModel;
   setTimeout(() => {
      this.innerNgModel.control.setValue(this.ngModel.model);
   })
}

plunkr