'angular material .textarea don't update follow variable
I tried to upload the Textfile into Textarea and edit it, but whenever I type and then upload it. Textarea will not update the contents of the files from the textfile. if you write into textarea defore upload .txt data in file not show. file.js
import { Component, OnInit, ViewChild, ElementRef } from "@angular/core";
/**
* @title Input with a clear button
*/
@Component({
selector: 'input-clearable-example',
templateUrl: './input-clearable-example.html',
styleUrls: ['./input-clearable-example.css'],
})
export class InputClearableExample {
@ViewChild("clrInput", { static: false }) clr: ElementRef;
constructor() {}
textArea: any;
row=15
onChange(value) {
this.textArea = value
console.log(this.textArea)
}
//upload
onFileSelect(event) {
const selectedFile = event.target.files[0];
const reader = new FileReader();
reader.onload = (e) => {
const text = reader.result.toString().trim();
if (this.textArea === undefined)
{
this.onChange(text)
}
else
{
var value=this.textArea + "\n" + text;
this.onChange(value)
}
};
this.clr.nativeElement.value = "";
reader.readAsText(selectedFile);
}
ngOnInit() {
}
}
> file.html
<input
type="file"
id="file-button-id"
accept=".txt"
(change)="onFileSelect($event)"
#clrInput
/>
<mat-form-field appearance="outline">
<textarea matInput rows="{{row}}" (keyup)="onChange($event.target.value)">
{{this.textArea}}</textarea>
</mat-form-field>
Solution 1:[1]
One solution is The formControl:
export class InputClearableExample {
@ViewChild("clrInput", { static: false }) clr: ElementRef;
constructor() {}
row = 15;
textArea = new FormControl("");
onChange(value: any) {
this.textArea.setValue(value);
console.log(this.textArea.value);
}
//upload
onFileSelect(event: any) {
const selectedFile = event.target.files[0];
const reader = new FileReader();
reader.onload = e => {
const text = reader.result ? reader.result.toString().trim() : "";
var value = this.textArea.value + "\n" + text;
this.onChange(value);
};
this.clr.nativeElement.value = "";
reader.readAsText(selectedFile);
}
ngOnInit() {}
}
and add [formControl]="textArea"
to your textarea tag like this:
<input
type="file"
id="file-button-id"
accept=".txt"
(change)="onFileSelect($event)"
#clrInput
/>
<mat-form-field appearance="outline">
<textarea
[formControl]="textArea"
matInput
rows="{{row}}"
(keyup)="onChange($event.target.value)"
>
</textarea>
</mat-form-field>
You can remove text {{textarea}}
between <textarea></textarea>
tag.
here a stackBlitz working example
Solution 2:[2]
(change)="onChange($event.target.value)"
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 | antoineso |
Solution 2 | Achraf Farouky |