简体   繁体   中英

Set default value of form field based on the dropdown selected by the user

I have a form where a user has to enter a bunch of info. I am using mat-select for one dropdown field. What I'm trying to do is set the default value of another form field based on the drop down selected by the user. How can I achieve this. Thanks in advance for your help.

Here is my template:

    <form [formGroup]="newFormGroup" (ngSubmit)="submit()">
        <div f>
         
            <mat-form-field appearance="fill" >
                <mat-label>Animal Sound</mat-label>
                <input matInput type="text" formControlName="animalSound" [(ngModel)]="sound" name="animalSound" class="form-control" id="animalSound">
            </mat-form-field>
            <mat-form-field appearance="fill" style="width: 10%;">
                <mat-label>Animal</mat-label>
                <mat-select formControlName="animal" [(ngModel)]="selectedValue">
                    <mat-option *ngFor="let animal of animals" [value]="animal.value">
                        {{animal.value}}
                    </mat-option>
                </mat-select>
            </mat-form-field>
        </div>
    </form>

Here is my ts code:

selectedValue: string;
  sound = 'bark';
  animals: AnimalType[] = [
    {value: 'Cat' },
    {value: 'Dog'}  ];
  newFormGroup = new FormGroup({
    animalSound: new FormControl('', Validators.required),
    animal: new FormControl('', Validators.required)

  });

So for example, If user selects dog, I want set the default value for the animal sound field as bark.

create a service which has a behavior subject;

@Injectable({provideIn: 'root'})
class DropdownService {
  value = new BehaviourSubject('Default')

  setValue(value: string){
    this.value.next(value);
  }

  getValue() {
    return this.value.asObservable();
  }
}

set value on dropdown component

then get value in form component

constructor(private dropdownService: DropdownService) {}

ngOnInit(){
// after your form initiated

this.dropdownService.getValue().subscribe(value => {
  this.form.controls.field.setValue(value)
});
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM