Home > Software engineering >  using angular reactive forms the defaults values i was setting in ngOnInIt are not getting reflected
using angular reactive forms the defaults values i was setting in ngOnInIt are not getting reflected

Time:12-16

When i was loading default values in ngOnInit in angular, using angular reactive forms the defaults values i was setting in ngOnInIt are not getting reflected. I'm using filter within the map

Based on URL I need the value in the map needs to be selected by default in the dropdown. Any help is appreciated.

tMap = [
  { url:"test", Name:'rony' },
  { url:"cool", Name:'rocky' }
];

ngOnInit() {
  this.loginForm.controls['hub'].setValue('rony');
  this.url = (window.location.href).substring(22,26);

  const selectedHub: { url:string, Name: string } = 
    this.tMap.filter(ele => ele.url == this.url)[0];
  this.loginForm.controls['hub'].setValue(selectedHub.Name);
}

HTML Code:

<div>
<select formControlName="hub" ng-model="hub" id="login" 
style="font-family: Arial; font-size: 12px; background-color: white; font-weight: 600">
<option *ngFor="let h of tMap"><a [href]="h.url">{{h.Name}}</a></option>
</select>
</div>

CodePudding user response:

You are missing [value] in your select option:

<option *ngFor="let h of tMap" [value]="h.Name">
  <a [href]="h.url">{{ h.Name }}</a>
</option>

With that, Angular now knows what to bind to. Also, remove ng-model from select, first of all it is AngularJS syntax, secondly you are already using the formcontrol, so no need to use [(ngModel)] (which is the Angular syntax).

  • Related