Search code examples
formsangularangular-ngmodel

Set initial value to select within custom component in Angular 4


As you can see in this plunkr (https://plnkr.co/edit/3EDk5xxSLRolv2t9br84?p=preview) I have two selects: one in the main component behaving as usual, and one in a custom component, inheriting the ngModel settings.

The following code links the innerNgModel to the component 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;
}

It works, since the name property is updated by both selects.

However when it first loads the second select has no selection.

I guess I'm missing something, a way to initialize the innerNgModel with the initial value.


Solution

  • This is a weird situation to do something like this, but I believe to get this working they need to implement another life-cycle hook. AfterModelSet or something like that :)

    Anyways, you can solve this with a simple setTimeout and a setValue:

    ngAfterViewInit() {
       this.ngModel.valueAccessor = this.innerNgModel.valueAccessor;
       this.innerNgModel = this.ngModel;
       setTimeout(() => {
          this.innerNgModel.control.setValue(this.ngModel.model);
       })
    }
    

    plunkr