Discovering updates to a read-only input's [ngModel] binding in an Angular 2 directive

One issue I'm facing is with a directive that sets the height of a textarea dynamically based on its content:

@Directive({
  selector: '[fluidHeight]',
  host: {
    '(ngModelChange)': 'setHeight()'
  }
})

export class FluidHeightDirective implements AfterViewInit {

  constructor(private elementRef: ElementRef) {}

  ngAfterViewInit() {
    this.setHeight();
  }

  @HostBinding('style.height.px')
  height: number;

  setHeight() {
    console.log(true)
    this.height = this.elementRef.nativeElement.scrollHeight;
  }
}

However, when combining [ngModel] with readonly, I encounter problems:

<textarea [ngModel]="foo" fluidHeight readonly></textarea>

Another textarea modifies the content in the read-only input field.

I've attempted to use ngModelChange, change, and input, but none seem to resolve the issue.

If anyone has a solution for this, please share!

Answer №1

One effective solution is to use a setter:

export class AutoAdjustHeightDirective implements AfterViewInit {

    @Input('autoAdjustHeight')
    set content(content:any) {
        this.adjustHeight();
    }

    constructor(private elementRef: ElementRef) {}

    ngAfterViewInit() {
        this.adjustHeight();
    }

   @HostBinding('style.height.px')
    height: number;

    adjustHeight() {
        console.log(true);
        this.height = this.elementRef.nativeElement.scrollHeight;
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible for a node and @angular/cli based application to function without an internet connection?

As a newcomer to the world of angular/cli and node, I am eager to build an application using Angular and deploy it to an environment where all external communication is blocked by a firewall. In this restricted setting, even accessing search engines is imp ...

Displaying a specific item with an icon in a list for user interaction in Ionic 3

Currently, I am working on a brand new music application. As part of my project, I have curated an extensive list of songs displayed on the homepage. My objective is to implement a feature where when a user clicks on a specific song from the list, it will ...

Struggling to retrieve a particular value in Angular, but encountering difficulties

I am attempting to retrieve information from my Firestore Collection. Everything works fine when I print the JSON data, but I am encountering issues when trying to display a single value. In order to fetch the data, I have implemented the following code: ...

What is the best way to execute multiple functions simultaneously in Angular?

Within a form creation component, I have multiple functions that need to be executed simultaneously. Each function corresponds to a dropdown field option such as gender, countries, and interests which are all fetched from the server. Currently, I call th ...

"Encountered a TypeError while attempting to send a server action to a custom

My custom form component, <ClientForm>, is built using Radix Primitives. "use client"; import { FC } from "react"; import * as Form from "@radix-ui/react-form"; const ClientForm: FC = (props) => ( <Form.Root {.. ...

Why does the server attempt to load the chart in Angular 10 Universal using Amcharts 4?

I have experience with Angular, but I am now delving into the world of using Universal for SEO purposes. My goal is to integrate a map from amcharts 4, which works fine without Angular Universal. However, I am facing an issue where the server attempts to ...

typescript: tips for selecting a data type within an object

I need help extracting the type of the 'name' property from an object belonging to the Action interface. interface Action { type: string, payload: { name: string } } I attempted to use Pick<Action, "payload.name">, but it didn&apos ...

Firebase Error: Page Not Found

I recently set up an Angular2 application and added Firebase using npm. I successfully imported it into my app.component.ts without any errors showing up in my text editor. The package.json file also indicates that Firebase is installed correctly. However ...

Angular 2 is throwing an error because it is unable to access the property 'comments' of an undefined value

After ensuring that all {{article.}} properties are functioning properly and displaying correctly on the webpage, there seems to be an issue with article.comments (located at the bottom of the HTML) showing as undefined even though it is the input for the ...

How to style a parent div with a background class in Angular 6

In my Bootstrap 4 project, I am creating an accordion that consists of cards. Each card contains various icons such as edit, view, and details. When any of these icons are clicked, a function in the component is triggered to navigate the user to a child ro ...

Experimenting with Jest testing for a Component or Service that includes the use of "declare var" functionality

During the testing of my component or service, an error has occurred: ReferenceError: flagPath is not defined The variable flagPath is sourced from a configuration file named config.js within the assets folder. Is there a method to incorporate it into ...

Angular click switch Component keeps track of its previous state

I recently developed an Angular component that consists of a button and an icon. One key requirement is for each instance of this component to retain its own status. For example, let's say we have three instances in the app.component.html: <app-v ...

Vue.js is unable to recognize this type when used with TypeScript

In my code snippet, I am trying to set a new value for this.msg but it results in an error saying Type '"asdasd"' is not assignable to type 'Function'. This issue persists both in Visual Studio and during webpack build. It seems like Ty ...

What is the proper way to declare and utilize a constant list within a component template in NuxtJs?

Can someone help me with using itemList in a template? The itemlist is a static list, but I am unsure of where to declare it and how to export it to the template. <template> <table class="table table is-striped is-narrow is-fullwidth" ...

Can a constant be utilized as the property name within routerLink when specifying queryParams?

I am currently trying to update the current page by modifying or adding the query parameter "categoryId". When I attempt: <a [routerLink]="" [queryParams]="{ categoryId: category!.id }" queryParamsHandling="mer ...

Executing a dual ajax request in Angular 5

I am attempting to perform two HTTP requests consecutively, with the second request depending on the result of the first. However, it seems like I am overlooking something: getParkingSpots(date) { var gmt = this.getTimezone().subscribe(data=>{ if(d ...

Socket.io: The other client will only update when there is interaction happening

I am currently facing a challenge setting up a real-time application using socket.io in Angular and node.js. The application is not functioning as expected. When a client makes a new post, the other clients do not receive updates until there is some inter ...

Issues with implementing Bootstrap icons in Angular are hindering functionality

As a beginner in Angular, I am currently working on creating a simple website using Angular and a Bootstrap template. However, I have encountered many issues along the way. Right now, I am struggling to utilize Bootstrap icons in my project. It appears tha ...

Encountering an issue with Angular2 where it is unable to load a JSON file, presenting the error message: "Cannot resolve all parameters

I've been trying to incorporate a json file into my Angular app, but I can't seem to pinpoint the issue. The error message keeps indicating that it cannot resolve all parameters of my component. (I had no trouble loading data directly from the c ...

What is the proper way to employ if and else if statements within Angular2?

Here's a question that has been duplicated on my How to utilize *ngIf else in Angular? post! ...