Home > database >  How to change total div when i select an option in Angular
How to change total div when i select an option in Angular

Time:04-28

app.component.html:

<div >
  <div >
    <div >
      <label   for="type" >Select Type<span >*</span>
      </label><br>
      <select  name="role" id="type" >
        <option value="">Select the type</option>
        <option value="option1" >option1</option>
        <option value="option2">option2</option>
        <option value="option3">option3</option>
        <option value="other">Other</option>
      </select>
    </div>
  </div>
</div>

<div>1</div>
<div>2</div>
<div>3</div>

If I select option1 then I need to display 1st div. If I select the option2 then I need to display 2nd div.

Thanks

CodePudding user response:

You need a selectedOption property in your component which you bind to ngModel changes on the <select> element.

You then can bind this property to the <div> elements using *ngIf.

<div >
<div >
 <div  >
   <label   for="type" >Select Type<span >*</span>
   </label><br>
   <select  name="role" id="type" [(ngModel)]="selectedOption">
     <option   value="">Select the type</option>
     <option   value="option1" >option1</option>
     <option   value="option2">option2</option>
     <option   value="option3">option3</option>
     <option   value="other">Other</option>
   </select>
 </div>
</div>

<div *ngIf="selectedOption === 'option1'">1</div>
<div *ngIf="selectedOption === 'option2'">2</div>
<div *ngIf="selectedOption === 'option3'">3</div>
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  public selectedOption;
}

StackBlitz example

CodePudding user response:

<div >
    <div >
        <div >
            <label  for="type">Select Type<span >*</span>
            </label><br>
            <select  name="role" id="type" 
                (change)="selectedValue = $event.target.value">
                <option value="">Select the type</option>
                <option value="option1">option1</option>
                <option value="option2">option2</option>
                <option value="option3">option3</option>
                <option value="other">Other</option>
            </select>
        </div>
    </div>
</div>

<div *ngIf="selectedValue == 'option1'">1</div>
<div *ngIf="selectedValue == 'option2'">2</div>
<div *ngIf="selectedValue == 'option3'">3</div>

@Component({
    selector: 'app-dashboard',
    templateUrl: './dashboard.component.html',
    styleUrls: ['./dashboard.component.css']
  })
  export class DashboardComponent implements OnInit {
    public selectedOption;
    constructor() { }
  
    ngOnInit(): void {}
  
  }
  • Related