Within my TypeScript code, there exists a variable named type
whose value is provided by its parent component. This type
value is essentially a string that has the possibility of being empty upon being received from the parent component. Additionally, in this particular file, I have implemented code that will be utilized for form validation.
@Input() public type = '';
constructor(private fb: FormBuilder) { }
public ngOnInit() {
this.myForm.get('type').valueChanges.subscribe(res => {
// carry out necessary actions
});
}
public myForm = this.fb.group({
myType: [this.type, Validators.required],
});
Switching over to the HTML side of things, I've created a form group labeled as myForm
which includes a mat-select dropdown element. The value of the mat-select is directly tied to the type
variable - essentially, if the type
contains a valid value passed down by the parent, it will automatically appear as the default selection within the dropdown menu. On the other hand, if the type
happens to possess an empty string value, users are then required to manually select an option from the dropdown list. Furthermore, the mat-select features a formControlName attribute for later validation purposes done in the TypeScript code.
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
<div>
<mat-form-field appearance="outline">
<mat-label>Type</mat-label>
<mat-select [(value)]="type" formControlName="myType">
<mat-option *ngFor="let t of types; let i=index" [value]="t">
{{t}}
</mat-option>
</mat-select>
</mat-form-field>
</div>
<button mat-button type="submit"
[disabled]="myForm.invalid">Submit</button>
</form>
The crux of my dilemma lies in the fact that when I introduce the formControlName
attribute, it appears to disrupt the binding between the mat-select and the value stored in the type
variable. Consequently, when type
holds a valid value inherited from its parent, this value fails to display as the default choice in the dropdown menu, thus requiring users to actively pick an item from the list. Despite this setback, retaining the formControlName
tag is essential for subsequent validation checks once the submit button is pressed.
Is there any workaround available that would enable the default selection in the mat-select to reflect the value contained in the type
variable, provided it's valid? Meanwhile, in scenarios where type
remains an empty string, users should still be prompted to make a selection from the dropdown, with the added assurance that the form control validates their choice accordingly.