'textarea with angular material not size properly on launching page
I'm facing a weird issue that I cannot understand. When one of my page is displaying I have my textarea cut as we can see in this image
But when I resize just a little the page or I just open the console (which probably resize the page too), the text appears completely
It's a form and I have the possibility to edit it, and when I do, and save, text appears completely too, the problem only happen when the page is just launched.
I use angular material and simple textarea like this :
<textarea matInput
cdkTextareaAutosize #autosize="cdkTextareaAutosize"
cdkAutosizeMinRows="1" cdkAutosizeMaxRows="25"
</textarea>
just for info it's inside a "ng-template" but don't think it changes anything. I don't want to fix a specific height as you imagine because it should be dynamic depending on the text length.
Do you have any idea of where could it come from ? And how can I workaround it ? Thank you for your answers.
Solution 1:[1]
Well, I found a hack which is not really beautiful in the end but work anyway.
I added a class on my textarea tag; I've already had a "ngAfterViewInit" in my typescript class so inside :
const textArea = document.getElementsByClassName('text-area-class')[0];
const textAreaHeight = window.getComputedStyle(textArea).height;
const newHeight = (parseFloat(textAreaHeight.split('px')[0]) * 1.3);
txtArea.setAttribute('style', `height: ${newHeight}px`);
The value of 1.3 is arbitrary and just has been tested to fit the most with my needs. I know it's not the most beautiful way to achieve it.
Solution 2:[2]
The core reason behind this why it's not working is that the textarea
size is calculated before being rendered. Try removing the auto height
property, and set a fixed line-height
to it.
Example:
textarea {
/*height: auto !important;*/
resize: none;
line-height: 3 !important;
}
Hope this helped.
Solution 3:[3]
had the same issue, solved it by leveraging the ChangeDetectorRef markForCheck() method after view is initialized.
in the constructor:
constructor(private changeDetRef: ChangeDetectorRef) {}
in the ngAfterViewInit code:
ngAfterViewInit(): void {
this.changeDetRef.markForCheck();
}
make sure your class implements AfterViewInit, for example -
export class MyAwesomeComponent implements AfterViewInit
by the way, in my specific case i've been using OnPush change Detection strategy
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 | Shaï |
Solution 2 | Mohamed.Karkotly |
Solution 3 | gil |