Value that is constantly changing for ngModel

Is it possible to use a function as a value for ngModel in Angular? I need to be able to set the value for my input at a later point in time, so I want to check if the function exists before updating the model. However, the following code snippet is not functioning as expected:

@Component({
    selector: 'string-editor',
    template: `
    <dl>
      <dt>{{propertyName}}</dt>
      <dd>
        <input
          type="text"  
          [(ngModel)]="getValue()" />
      </dd>
    </dl>`,
})
export class StringEditor {

    @Input()  public propertyName: string;
    @Input()  public entity: any;

    getValue() {
      return this.entity ? this.entity[this.propertyName] : ''
    }
};

Answer №1

It's not possible to directly pass a function to [(ngModel)], however, you can achieve the same outcome by splitting the binding and incorporating the checks within the binding itself

<input
  [ngModel]="entity ? entity[propertyName] : null"
  (ngModelChange)="entity && propertyName ? entity[propertyname] = $event: null"

Answer №2

Avoid using functions in bindings. Here's an alternative approach:

[(ngModel)]="someValue"             //<<===updated



export class StringEditor {

    @Input()  public propertyName: string;
    @Input()  public entity: any;

    ngOnInit(){                     //<<<===included
       this.someValue=this.entity ? this.entity[this.propertyName] : ''
    }
};

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

Setting up ESLint and Prettier for Accurate Error Detection in TypeScript and Next.js Development

As I work with TypeScript and Next.js, I decided to implement strict code formatting rules by adding the following configuration to my eslintrc.json file: "rules": { "prettier/prettier": "error" } However, when I ran npm ru ...

Angular is not properly integrating Bootstrap features

I've been attempting to create bootstrap accordion items, but unfortunately they're not functioning correctly as shown in the Bootstrap documentation or YouTube tutorials. In my angular.json file, I have included both bootstrap and jQuery for te ...

What is the best way to generate an object in TypeScript with a variety of fields as well as specific fields and methods?

In JavaScript, I can achieve this using the following code: var obj = { get(k) { return this[k] || ''; }, set(k, v) { this[k] = v; return this; } }; obj.set('a', 'A'); obj.get('a'); // returns &ap ...

When using ngx-slider in Angular, it unexpectedly fires off when scrolling on mobile devices

I am currently developing a survey application that utilizes ngx-sliders. However, I have encountered an issue on mobile devices where users unintentionally trigger the slider while scrolling through rows of slider questions, resulting in unintended change ...

Ignoring TypeScript overloads after the initial overload declaration

Issue An error occurs when attempting to call an overload method for a specific function. The call only works for the first defined overload, causing an error if the call is made to the second overload with mismatched typing compared to the first overload ...

Struggling with "Content" not being recognized in Typescript PouchDB transpilation errors?

I have been diligently working on an Ionic app for the past three months with no major issues during development or deployment to mobile devices. However, yesterday I encountered a frustrating NPM dependency problem while trying to deploy to mobile. In an ...

Exploring the fusion of different interfaces and props in React using typescript

I have designed an interface as shown below, representing the "base button". export interface ButtonProps { backgroundColor?: Colors, children?: React.ReactNode | JSX.Element, style?: CSSProperties, disabled?: boolean, onClick?: () => ...

typescript import { node } from types

Exploring the possibilities with an electron application developed in typescript. The main focus is on finding the appropriate approach for importing an external module. Here is my typescript configuration: { "compilerOptions": { "target": "es6", ...

Show a specific form field based on the chosen option in a dropdown menu using Angular and TypeScript

I am looking to dynamically display a form field based on the selected value from a dropdown list. For instance, if 'first' is chosen in the dropdown list, I want the form to remain unchanged. However, if 'two' is selected in the drop ...

Is it possible to send all API requests through the server side in an Angular Universal application?

I have integrated angular universal into my angular project and I am looking to ensure that all API requests, both post and get, are made from the server side rather than the client side. Is it possible to achieve this functionality in Angular? For exampl ...

What sets aws-cdk-lib apart from @aws-cdk/core, @aws-cdk/aws-iam, and others?

There seems to be a variety of examples out there using the AWS CDK, with some referencing aws-cdk-lib and others using @aws-cdk/core. Can someone clarify the distinction between these two and provide guidance on when to use one over the other? ...

The null error occurs when rendering with React's state array

When I try to call an API that emits JSON, I am encountering an issue. I call the promise API function in componentDidMount, set the state, and then call it in the render method, but it always returns a null error. I need assistance, please. Interface fo ...

How can I adjust the font size property for Material UI Icons through typing?

I put together the code snippet below, and I'm trying to define a specific type for the custom iconFontSize prop. Can someone guide me on how to achieve this? import { SvgIconComponent } from '@mui/icons-material' import { Typography, Typogr ...

Steps for creating user accounts and saving user information in Firebase's Real Time Database

Can someone please guide me on how to register a user in Firebase and save their additional details such as first name, last name, etc.? I have created a standard registration form in Angular and successfully registered users with their username and pass ...

Software designed for apple silicon ARM64 running Electron framework

Running the Electron desktop application successfully on X64 using electron-builder and dmg. Now, if we need to run the same application on Apple Silicon (ARM64), we followed the steps below: Installed Xcode 12 and upgraded Mac to Big Sur. Executed " ...

Accessing data from the subscribe method

When attempting to use certain values for graphs, I encountered an issue where the value returned becomes undefined once outside of the subscribe function. I have experimented with putting the values in an array of objects but still believe this is the co ...

Ways to remove cdk-overlay-container

I am currently working on an Angular project (version 9.1.4) that utilizes ng-bootstrap (version 6.1.0) to display modals. I have observed that whenever a modal is opened, it adds <div class='cdk-overlay-container' /> to the HTML structure. ...

Accessing Nested Arrays in Angular 8: Retrieving Data in HTML Template from Multiple Layers of Arrays

Hello there. I'm using an API that gives me the following data: (4) [{…}, {…}, {…}, {…}] 0: dueDate: "2018-03-26T00:00:00" priority: {priorityId: 1, priorityName: "Critical", priorityColor: "red"} statuses: Array(1) 0: ...

Issue: Error message - Unhandled promise rejection: NodeInjector error - ControlContainer not found

I'm having trouble validating a form and encountering an error. I tried implementing the suggestions provided in the following threads without success: Getting error suddenly in Angular Error: NodeInjector: NOT_FOUND [ControlContainer] Using forms i ...

Monitoring URL changes in Angular2 using the HostListener

I have a common navbar component that is included in every page of my website. I would like it to detect when the URL changes using a HostListener. @HostListener('window:hashchange', ['$event']) onHashChange(event) { this.checkCu ...