'Convert form control value to string

Hey I created an input field as form control. The input value will be added to a formArray everytime user enters the message.

export class AppComponent { 
      inputText = this.fb.control('', Validators.required);
      inputArray = this.fb.array([]);

      constructor(private fb: FormBuilder) {}
      


     
   

     **text:string;**
            public addInputIntoArr() {
                      this.inputArray.push(this.fb.control(this.inputText.value));
**this.text=this.inputText.value;**
    this.inputText.reset();
                
            }

HTML:

<textarea
                matInput             
                [formControl]="inputText"
                required=""
                (keyup.enter)=addInputIntoArr()
            >
            </textarea>

For a function I need the value of the input field as type string. I tried this:

this.inputText.value

But I get the information that type string is required. Now to my question, is it possible to convert a form control value to type string and if yes, how can this be done.

I would be very gratefult for any answers and look forward to learning new things.

Solved: I created a variable to store this.inputText.value, I then use the value of this variable in the function instead of inputText.value. It is working fine, but I am not sure if this is best case. This is what I come up with, if anyone has other ideas or approach I will be glad to hear :)



Solution 1:[1]

Since you do not need a complete form but just one formControl (judging from your example), please try this:

in your ts class:

inputText = new FormControl('', Validators.required);

You can then access the value with this.inputText.value, You can also listen to changes:

this.inputText.valueChanges.subscribe({
    next: value => doSomethingWith(value),
    error: () => handleError
});

(Do not forget to unsubscribe later.)

In your template, you can remove required=""

You can also apply styling for an invalid textfield (like a red border) by referring to inputText.invalid in your template to create/refer to a class, e.g.:

[ngClass]="{'border-red': inputText.invalid}"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 jona303