Home > Enterprise >  Why textarea doesnt display real value of formControl if i use matAutocomplete
Why textarea doesnt display real value of formControl if i use matAutocomplete

Time:09-14

  <textarea
  matInput
  type="text" 
  [disabled]="isTypingNotAvailable"
  [rows]="rowsCount"
  placeholder="Type text ..."
  formControlName="text"
  (keydown.control.enter)="onCtrlEnter()"
  (keydown.enter)="onEnter($event)"
  [matAutocomplete]="auto"
></textarea>

When i call this code:

this.sendMessageForm.get('text').setValue('Hi');

I see how the given text is placed in the form, but in the textarea (visually) it is not displayed, why?

see that https://stackblitz.com/edit/angular-ivy-plhchb?file=src/app/app.component.html

CodePudding user response:

The problem is the displayWith property on the mat-autocomplete component is preventing the control value from being set programmatically with a plain string.

The displayFn callback function provided is preventing the form control from being set with a plain string. You could either remove the displayWith property, or update the displayFn to allow a plain string to be set, or set the control value using an object {value: 'my string'} instead of a string.

1. Remove the displayWith property from the autocomplete component.

//template

<mat-autocomplete 
    #auto="matAutocomplete" 
    [displayWith]="displayFn" <-- remove
>

2. Update the displayFn method to allow your manual changes.

// component.ts

  displayFn(template): string {
    return template && template.value ? template.value : template;
  }

3. Update the control.setValue() method to work with the displayFn.

Set the control value by pass in an object with i.e., control.setValue({value: 'my string'}).

// component.ts

  initForm() {
    this.sendMessageForm = this.fb.group({
      test: [{value: 'Initial text'}],  <-- need to use object {value: 'string'}
    });
  }

  ...

  addText() {
    this.sendMessageForm?.get('test').setValue({value: 'hi'});
  }

CodePudding user response:

The problem is not about textarea or setting value. It is about matAutocomplete directive on it. So I removed the directive and the problem is gone. It seems textarea is not compatible with matAutocomplete.

  • Related