I insert a textarea component into my template like so:
<div class="card-body" *ngIf="isEditing">
<app-text-area input-id="body" input-value="This is my default input value"></app-text-area>
</div>
The template of app-text-area
is like so:
<textarea
placeholder="This is my placeholder"
[name]="inputID"
(input)="onInputChanged($event)"
ngModel>
{{ inputValue }}
</textarea>
The subsequent rendered HTML is like so:
<textarea _ngcontent-owj-c62="" placeholder="This is my placeholder" ngmodel="" ng-reflect-model="" ng-reflect-name="body" class="ng-pristine ng-valid ng-touched">
This is my default input value
</textarea>
However on the actual page, the inputValue
text doesn't show up anywhere, the textarea acts as though it is empty, even showing the placeholder text. I can see the value in the html, though when I start typing in the box it replaces it as if it weren't there. The console shows no errors.
If I remove ngModel
from the textarea, it fixes it
My app-text-area
component ts is:
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { ControlContainer, NgForm } from '@angular/forms';
@Component({
selector: 'app-text-area',
templateUrl: './text-area.component.html',
viewProviders: [ { provide: ControlContainer, useExisting: NgForm } ],
styleUrls: ['./text-area.component.scss']
})
export class TextAreaComponent implements OnInit {
@Input("input-id") public inputID: string = "text";
@Input("input-value") public inputValue: string;
constructor() { }
ngOnInit(): void {
}
public onInputChanged(event: Event):void {
let newValue = (event.target as HTMLTextAreaElement).value;
this.inputValue = newValue;
}
}
CodePudding user response:
Hard to help without seeing the component.ts file But a solution would be something in the lines of the following:
HTML template:
<textarea
[name]="inputID"
(input)="onInputChanged($event)"
[value]="inputValue">
</textarea>
<p>{{inputValue}}</p>
And the component.ts:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-text-area',
templateUrl: './text-area.component.html',
styleUrls: ['./text-area.component.css']
})
export class TextAreaComponent implements OnInit {
inputID:number=1;
inputValue:string="This is my placeholder";
constructor() { }
ngOnInit(): void {
}
onInputChanged(event:any){
this.inputValue=event.target.value;
}
}
This would set the initial value as "This is my placeholder" and would update the value on each change in the input displayed inside the p tag
CodePudding user response:
I managed to fix this by setting [ngModel]="inputValue"
instead of the defaultValue
, value
, or placing inputValue
inside the textarea itself.