[英]Set default value of form field based on the dropdown selected by the user
我有一个表单,用户必须输入一堆信息。 我正在为一个下拉字段使用 mat-select。 我要做的是根据用户选择的下拉菜单设置另一个表单字段的默认值。 我怎样才能做到这一点。 在此先感谢您的帮助。
这是我的模板:
<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>
这是我的 ts 代码:
selectedValue: string;
sound = 'bark';
animals: AnimalType[] = [
{value: 'Cat' },
{value: 'Dog'} ];
newFormGroup = new FormGroup({
animalSound: new FormControl('', Validators.required),
animal: new FormControl('', Validators.required)
});
例如,如果用户选择狗,我想将动物声场的默认值设置为吠声。
创建具有行为主体的服务;
@Injectable({provideIn: 'root'})
class DropdownService {
value = new BehaviourSubject('Default')
setValue(value: string){
this.value.next(value);
}
getValue() {
return this.value.asObservable();
}
}
在下拉组件上设置值
然后在表单组件中获取值
constructor(private dropdownService: DropdownService) {}
ngOnInit(){
// after your form initiated
this.dropdownService.getValue().subscribe(value => {
this.form.controls.field.setValue(value)
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.