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

What is the trick to make the "@" alias function in a Typescript ESM project?

My current challenge involves running a script using ESM: ts-node --esm -r tsconfig-paths/register -T src/server/api/jobs/index.ts Despite my efforts, the script seems unable to handle imports like import '@/server/init.ts': CustomError: Cannot ...

Tips for creating ternary operator logic that account for numerous conditions and optional parameters:

Trying to create a logic for my validator functions that involves using objects as errorMaps for input validation. In the code snippet provided, args.drugName is an optional field. If the user provides text, we want to ensure it is greater than 3 letters; ...

Utilizing next-redux-wrapper within the getServerSideProps function in Next.js allows for seamless

When trying to call an action function in getServerSideProps using TypeScript, I encountered some challenges. In JavaScript, it is straightforward: import { wrapper } from "Redux/store"; import { getVideo } from "Redux/Actions/videoAction&qu ...

conflict between ng-content and textarea elements

My custom component called my-textarea has a unique template structure: <textarea> <ng-content></ng-content> </textarea> However, when I try to input text into the component using the same method as a regular textarea HTML eleme ...

Vue.js Element UI dialog box

Is there a method to customize the close button in el-dialog and replace it with my own design? For instance, can I change the default close button located at the top left corner of the dialog? <el-dialog title="Tips" :visible.sync=" ...

Issue C2039: 'IsNearDeath' cannot be found within 'Nan::Persistent<v8::Object,v8 ::NonCopyablePersistentTraits<T>>'

After updating my nodejs to v12.3.1, I encountered errors when attempting to execute npm install in my project directory. error C2059: syntax error: ')' (compiling source file ..\src\custo m_importer_bridge.cpp) error C2660: 'v8 ...

RXJS: Introducing a functionality in Observable for deferred execution of a function upon subscription

Implementing a Custom Function in Observable for Subscribers (defer) I have created an Observable using event streams, specifically Bluetooth notifications. My goal is to execute a function (startNotifictions) only when the Observable has a subscriber. ...

Tips for adding a class to the end of the DOM class

Greetings! I'm currently working with the code below: for ( let x: number = 0; x < this._vcr.element.nativeElement.querySelectorAll(".ui-steps-item").length; x++) { let className: any = this._vcr.element.nativeElement.querySelectorAll( ...

Extracting and retrieving the value from the paramMap in Angular/JavaScript

How can we extract only the value from the router param map? Currently, the output is: authkey:af408c30-d212-4efe-933d-54606709fa32 I am interested in obtaining just the random "af408c30-d212-4efe-933d-54606709fa32" without the key "authke ...

What is the solution for fixing the Typescript error in formik onSubmit?

I encountered an error while using the onSubmit prop of Formik: The type '(values: { email: string; password: string; }) => { type: string; payload: { email: string | null; password: string | null; }; }' is not compatible with the type '(( ...

Instructions for opening a URL in a new tab using Angular

Within my Angular 10 application, I am conducting an API call that retrieves an external URL for downloading a pdf file. Is there a method to open this URL in a new browser tab without relying on the window object? I've been using window.open(url) suc ...

Working with TypeORM to establish two foreign keys pointing to a single primary key in a table

For my project, I am looking to establish bi-directional ManyToOne - OneToMany relationships with two foreign keys that reference the same primary key. Specifically, I have a 'match' table that includes two players from the 'player' tab ...

I encountered an unexpected obstacle while reloading my Next.js application with animejs. The error message reads: "SyntaxError: Unexpected token 'export'." This unwelcome occurrence took place during the

Encountering an error with animejs when reloading my Next.js app: An unexpected token 'export' is causing a SyntaxError. This issue occurred during the page generation process. The error originates from file:///Users/.../node_modules/animejs/lib ...

Using Angular and Firestore to push matched properties into an array

Module 1 this.service.myArray['bands'] = data; Module 2 Module two is designed to receive artist IDs individually through an @Input attribute. Following that, a query is executed to retrieve all relevant albums. Each album entry includes an &ap ...

Angular Build Showing Error with Visual Studio Code 'experimentalDecorators' Configuration

Currently experiencing an issue in VSC where all my typescript classes are triggering intellisense and showing a warning that says: "[ts] Experimental support for is a feature that is subject to change in a future build. Set the 'experimentalDeco ...

When defining a GraphQL Object type in NestJS, an error was encountered: "The schema must have unique type names, but there are multiple types named 'Address'."

Utilizing Nestjs and GraphQL for backend development, encountered an error when defining a model class (code first): Schema must contain uniquely named types but contains multiple types named "Address". Below is the Reader model file example: @ObjectType() ...

Retrieve parent form validation within a child component Angular 5 control value accessor

I found helpful information on this website: My goal is to implement validation for all fields in a child component using control value accessor and template driven forms. (For reference, here is the link to the issues on Stackblitz: https://stackblitz.c ...

Angular displays incorrect HTTP error response status as 0 instead of the actual status code

In Angular, the HttpErrorResponse status is returning 0 instead of the actual status. However, the correct status is being displayed in the browser's network tab. ...

How to iterate through the elements of an object within an array using Vue.js and TypeScript

There was an issue with rendering the form due to a TypeError: Cannot read properties of undefined (reading '0'). This error occurred at line 190 in the code for form1.vue. The error is also caught as a promise rejection. Error Occurred <inpu ...

Challenges encountered while deploying a NextJS project with TypeScript on Vercel

Encountering an error on Vercel during the build deploy process. The error message says: https://i.stack.imgur.com/Wk0Rw.png Oddly, the command pnpm run build works smoothly on my PC. Both it and the linting work fine. Upon inspecting the code, I noticed ...