Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Angular 5) *ngIf not working on Select/Options

I have a model Questionaire which has name property.

app.component.ts

import {Questionaire} from '../questionaire.model';

questionaire : Questionaire; 

Based on the name property of class Questionaire in my html code I need to display different option value of the select element using *ngIf this is what I am trying to do in app.component.html

<select 
 class="form-control" 
 name="proposal" 
 required 
 ngModel
 >
   <div *ngIf = "questionaire.name === 'credit'">
     <option value="">Select</option>
     <option value="Proposal">Proposal</option>
     <option value="ndg">NDG</option>
     <option value="credit">Credit Line</option>
   </div>
   <div *ngIf = "questionaire.name === 'asset'">
     <option value="">Select</option>
     <option value="Proposal">Proposal</option>
     <option value="asset">Asset</option> 
   </div>
 </select>

I am not able to achieve what I am trying to do.

I hope I am clear.

like image 756
Adnan Abdul Khaliq Avatar asked Jan 29 '23 23:01

Adnan Abdul Khaliq


1 Answers

You should really move your data logic inside the typescript part of your component. Your template should only contain presentation logic

public interface Kvp {
  value: string;
  label: string;
}

export class AppComponent implements OnInit {

  questionaire : Questionaire;
  options: Kvp[];

  ngOnInit(): void {
    if (this.questionnaire.name === 'credit') {
      this.options = [
        {value: 'Proposal', label: 'Proposal'},
        {value: 'ndg', label: 'NDG'}
      ];
      // You can do the rest ;-)
    }
  }

}

Then, inside your template, simply iterate through "options"

<select class="form-control" 
   name="proposal" 
   required 
   ngModel>
     <option value="">Select</option>
     <option *ngFor="let item from options" value="{{item.label}}">{{item.value}}</option>
</select>

note: You really shouldn't have any business logic inside your AppComponent. This component should only contain sub-components.

like image 130
Deblaton Jean-Philippe Avatar answered Jan 31 '23 18:01

Deblaton Jean-Philippe