角度文本区域输入不显示值/内容,尽管显示在html中



我在模板中插入一个文本区域组件,如下所示:

<div class="card-body" *ngIf="isEditing">
<app-text-area input-id="body" input-value="This is my default input value"></app-text-area>
</div>

app-text-area的模板是这样的:

<textarea
placeholder="This is my placeholder"
[name]="inputID"
(input)="onInputChanged($event)"
ngModel>
{{ inputValue }}
</textarea>

随后呈现的HTML如下所示:

<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>

然而,在实际页面上,inputValue文本不会显示在任何位置,文本区域就像是空的,甚至显示占位符文本。我可以在html中看到值,不过当我开始在框中键入时,它会替换它,就好像它不在那里一样。控制台没有显示任何错误。

如果我从文本区域删除ngModel,它会将其修复为

我的app-text-area组件ts是:

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;
}
}

如果没有看到component.ts文件,很难提供帮助但一个解决方案应该是以下几点:

HTML模板:

<textarea

[name]="inputID"
(input)="onInputChanged($event)"
[value]="inputValue">

</textarea>
<p>{{inputValue}}</p>

组件.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;

}
}

这将把初始值设置为"0";这是我的占位符";并且将在p标签内显示的输入的每次变化时更新值

我通过设置[ngModel]="inputValue"而不是defaultValuevalue或将inputValue放置在文本区域内来解决此问题。

最新更新