Skip to content
Advertisement

Why mat-option text is not rendering in view sometimes?

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

xyz = [
  { id: 'a', value: 'a'},
  { id: 'b', value: 'b'},
  { id: 'c', value: 'c'}
];
constructor(private fb: FormBuilder) {}

form = this.fb.group({
  field1: ['a']
});

get deletedValue() {
  return this.xyz.map(x => x.value).indexOf(this.form.value.field1)<0
  && this.form.value.field1 !== '';
}

action() {
  this.form.patchValue({
    field1: 'z'
  });
}

component.html

<form [formGroup]="form">
  <select formControlName="field1">
    <option *ngIf="deletedValue" class="d-none" [value]="form.get('field1').value">
                    {{ form.get('field1').value }}</option>
    <option *ngFor="let i of xyz" [value]="i.value">{{i.value}}</option>
  </select>
</form>
<br>
<button (click)="action()">Click</button>

Please help me out.

Advertisement

Answer

Please add this code in your component.ts in action function

action() {
    this.form.patchValue({
      field1: 'z'
    });
    this.xyz.push({id: this.form.controls['field1'].value, value: this.form.controls['field1'].value})
}

Then it will add the ‘z’ value in your dropdown option.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement