0

I'm trying to dynamically set the ngModel to bind two input elements together while having a default value come from one of them. I'm passing in data like

[
  {
     name: modelName,
     defaultValue: 'default'
  },
  {
     name: modelName
  }
]

And trying to get two input fields that are bound together that will both end up with that default value. This is just pretend data, It's coming in differently which is why they don't both have the default value.

I'm currently binding the fields like (not sure how to tie in the default value):

<div *ngFor="let data of dataArray">
  <input [(ngModel)]="models[data.name]" [name]="data.name" />
</div>

With the models array just being a variable in the component going off of this question/answer

canpan14
  • 1,181
  • 1
  • 14
  • 36

1 Answers1

1

You need to set the value of models[data.name] to the default value in the component for the model binding and default value to work properly. You can do this in ngOnChanges if the data is in an input to the component or you will need to do it in the subscribe of an observable if you are requesting the data from the server. Examples:

ngOnChanges

export class ExampleComponent implements OnChanges {
  @Input() public dataArray: { name: string, defaultValue: any }[];
  public models = {};

  ngOnChanges() {
    this.dataArray
      .filter((d) => !!d.defaultValue)
      .forEach((data) => {
        this.models[data.name] = data.defaultValue;
      });
  }
}

subscribe

export class ExampleComponent implements OnInit{
  public dataArray: { name: string, defaultValue: any }[];
  public models = {};

  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.http.get('/some/url').subscribe((dataArray) => {
      this.dataArray = dataArray;
      this.dataArray.filter((d) => !!d.defaultValue)
      .forEach((data) => {
        this.models[data.name] = data.defaultValue;
      });
    });
  }
}
Teddy Sterne
  • 13,774
  • 2
  • 46
  • 51
  • Thanks for the detailed answer! I figured it would have to be something around this method. The data is coming from multiple services that each get kicked off. I'll probably combine your subscribe method with a forkJoin to get it work. Otherwise I can have a middleman do the same thing and pass it in as an input. – canpan14 Jun 07 '18 at 23:42