Integrating Different forms with a select dropdown in Angular

Viewed 110

I have three different forms where the first form has a select dropdown with two values .. i want to know on selection of one of the dropdown options it must must open another sub form . I want to know how this can be achieved.

Below is code having the dropdown :

app.component.html

<mat-form-field>
  <mat-label>Favorite food</mat-label>
  <mat-select>
    <mat-option *ngFor="let food of foods" [value]="food.value">
      {{food.viewValue}}
    </mat-option>
  </mat-select>
</mat-form-field>

app.component.ts

import { Component } from '@angular/core';

interface Food {
  value: string;
  viewValue: string;
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'Food';
  foods: Food[] = [
    {value: '1', viewValue: 'value 1'},
    {value: '2', viewValue: 'value 2'},
  ];
}

The Other form Contains the following :

app.component.html

<h1>Value 1 is selected !!</h1>

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'form1';
}

Please help me with this where i can achieve : on click of a select dropdown option should navigate to another form ( in this case when value 1 is selected from drowdown, the new form containing "value 1 is selected" should be navigated

1 Answers

You can put an output on the mat-select to detect a change in value:

 <mat-select (selectionChange)="myMatSelectWasChanged($event)">
    <mat-option *ngFor="let food of foods" [value]="food.value">
      {{food.viewValue}}
    </mat-option>
  </mat-select>

Then in the .ts file you can navigate to the new form:

export class AppComponent {
  title = 'Food';
  foods: Food[] = [
    {value: '1', viewValue: 'value 1'},
    {value: '2', viewValue: 'value 2'},
  ];

  myMatSelectWasChanged(valueChange) {
    // enter code here
  }
}
Related