I have a form where there is a mat-select field. The mat-select field will show value even if the option doesn’t match the list of options. Please take a reference of this stackblitz example.
In this example, on button click, I am adding a value in a form that doesn’t match with theJSON values. The same thing I have implemented is working only on the initial page load but not on another button click. The get
function is though returning true
but in view, I cannot see the text in option.
component.ts
JavaScript
x
22
22
1
xyz = [
2
{ id: 'a', value: 'a'},
3
{ id: 'b', value: 'b'},
4
{ id: 'c', value: 'c'}
5
];
6
constructor(private fb: FormBuilder) {}
7
8
form = this.fb.group({
9
field1: ['a']
10
});
11
12
get deletedValue() {
13
return this.xyz.map(x => x.value).indexOf(this.form.value.field1)<0
14
&& this.form.value.field1 !== '';
15
}
16
17
action() {
18
this.form.patchValue({
19
field1: 'z'
20
});
21
}
22
component.html
JavaScript
1
10
10
1
<form [formGroup]="form">
2
<select formControlName="field1">
3
<option *ngIf="deletedValue" class="d-none" [value]="form.get('field1').value">
4
{{ form.get('field1').value }}</option>
5
<option *ngFor="let i of xyz" [value]="i.value">{{i.value}}</option>
6
</select>
7
</form>
8
<br>
9
<button (click)="action()">Click</button>
10
Please help me out.
Advertisement
Answer
Please add this code in your component.ts in action function
JavaScript
1
7
1
action() {
2
this.form.patchValue({
3
field1: 'z'
4
});
5
this.xyz.push({id: this.form.controls['field1'].value, value: this.form.controls['field1'].value})
6
}
7
Then it will add the ‘z’ value in your dropdown option.