Ensure that an input control consistently displays the value it is linked to

Here is the code snippet of the component:

@Component({
  template: `
  <form>
    <label>Enter your name:</label>
    <input #name name="name" [ngModel]="firstName" (change)="onNameChange(name.value)">
  </form>
  <p>Your name: {{firstName}}</p>`
})
export class AppComponent {
  firstName = 'John';

  onNameChange(value: string): void {
    if (value == "") {
      this.firstName = "John";
    }
    else {
      this.firstName = value;
    }
  }
}

Even after erasing all text and leaving the input control, the default text John does not reappear. This happens because the model remains unchanged.

How can I make sure that the input control always displays the current value of the model?

For more details, check out the Plunker related to this issue.

Answer №1

To access the FormControl, refer to the guidelines provided in the official documentation:

If you want to examine the properties of the associated FormControl, such as its validity state, you can export the directive into a local template variable using ngModel as the key (e.g., #myVar="ngModel"). This allows you to access the control through the directive's control property.

Update your template as follows:

<input #name name="name" [ngModel]="firstName" #m="ngModel" (change)="onNameChange(name.value, m.control)">

Next, modify the form control using the standard API:

onNameChange(value: string, ctrl): void {
  if (value == "") {
    ctrl.setValue('John');

Refer to this plunker for a demonstration.

This essentially mirrors the functionality of the ngModel directive. Take a look at the source code for more information.

Answer №2

If you recall, the model will be altered by the instructions provided

"Apple in the Basket"

<input #name name="name" [(ngModel)]="firstName" (change)="onNameChange(name.value)">

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

Encountering an error in Angular Material Table: Unable to define property 'filterPredicate' for undefined object

I am facing an issue with my Angular Material Table that has client-side filtering. The problem arose when I switched to retrieving data from a service instead of using hardcoded data. Now, I am receiving an error message saying: "Cannot set property &apos ...

enhancing the types of parameters in a function declaration without relying on generics

My goal is to improve developer experience (DX) by expanding the types for parameters in a function signature. I want the tooltip when hovering over the following function to provide more detailed information: type Props = { a: number; }; const func = ( ...

Troubleshooting CSS Issues in ASP.NET Boilerplate

I am attempting to apply a CSS style to a text input similar to the one found on the CreateUser default page. However, I am encountering an issue where the blue line under the textbox does not appear when I navigate away from and then return to the page. ...

The element is implicitly given an 'any' type due to the fact that a string expression cannot be used to index the following type: { "1" : { "key": string}; "2" : { "key": string};}

I have a JSON file containing IDs as keys like this: "1" : { "key": "value"}, "2" : { "key": "value"}, In my class, I import this JSON file as a data object and then use the ID passed to a method ...

Checking for null properties in Typescript objectsorHow to verify if a

What is a simple way to determine if the properties of an object in TypeScript are nullable? For example export default interface UserDto{ ID?:int; USER_NAME?:string; FIRST_NAME?:string; LAST_NAME?:string; USER_ROLE?: ...

The disappearing act of embedded Twitter timelines in Ionic 2

My code displays the timeline initially, but it disappears when I navigate away from the view. Can anyone help me troubleshoot this issue? Upon first visit to the view, the timeline is visible, but upon returning, it disappears. Below is the code snippet ...

Encountering a problem when utilizing window.ethereum in Next Js paired with ether JS

Experiencing some difficulties while utilizing the window.ethereum in the latest version of NextJs. Everything was functioning smoothly with NextJs 12, but after upgrading to NextJs 13, this error started popping up. Are there any alternative solutions ava ...

Various gulp origins and destinations

I am attempting to create the following directory structure -- src |__ app |__ x.ts |__ test |__ y.ts -- build |__ app |__ js |__ test |__ js My goal is to have my generated js files inside buil ...

Getting the string value from an observable to set as the source attribute for an

I am facing an issue with my image service. It requires the user_id to retrieve the id of the user's profile picture, followed by another request to get the JPG image associated with that id. To fetch the image, use this code snippet: <img [src]=" ...

The Node.js application is having trouble connecting to the Angular application on port 3000 when the Angular app is hosted on a remote machine

I'm facing an issue with my Nodejs app not being able to connect with the Angular app on port 3000 when the Angular app is hosted on a remote machine. However, everything works fine when both apps (Nodejs and Angular) are hosted on the same machine. C ...

Anglar2-useful-swiper does not automatically advance slides

I've been working on integrating the angular2-useful-swiper plugin into a single page application for image display, complete with auto rotation. However, I'm encountering an issue where the images are not transitioning as they should, and instea ...

Inject components in Angular using dependency injection

Can components in Angular be dependency injected? I am interested in a solution similar to injecting services, like the example below: my.module.ts: providers: [ { provide: MyService, useClass: CustomService } ] I attempted using *ngIf= ...

Updating a component in Angular 4.3.1 from within an observable callback

My Project Journey I am currently immersing myself in learning Angular by working on a personal project: developing a game that involves routing, services, and more. One of the requirements is to hide the header on the landing page (route for '/&apos ...

Is it feasible to access and modify local files within an Angular project using TypeScript code in the angular component.ts file? If so, how can this be achieved?

My Angular application is built on version 4 or higher. I have a setup in my project where there is a folder containing a txt file and another folder next to it with an angular component.ts file: FolderWithFile -----file.txt ComponentFolder -----person.co ...

Uploading Code to Github for the Second Round

After successfully building my Angular code and publishing it to the Github repository, I specified the directory as dist/projectname. As a result, only my dist folder is visible on the Github Pages in my repository. Now, I want to push the complete code ...

Is there a way in Typescript to determine the type of a union type when a specific condition is satisfied?

I am faced with a scenario where I have an object that can take on two different shapes: {ageTop:42} or {locations: [{name:Myrtle Beach}]} These objects are passed as parameters to a function, and I want to ensure that the function only receives the t ...

Converting JSON HTTP response to an Array in AngularJS 2: A Comprehensive Guide

As I work on a Http get request in Angular 2, the response returned is in JSON format. However, I am facing an issue when trying to use it in a ngFor loop because it is not formatted as an Array. Is there a way to convert JSON data to an Array in Angular ...

Retrieve the attributes of a class beyond the mqtt callback limitation

Currently, I am utilizing npm-mqtt to retrieve information from a different mqtt broker. My objective is to add the obtained data to the array property of a specific class/component every time a message is received. However, I'm facing an issue wher ...

The Angular 2+ page fails to load properly on Internet Explorer or SharePoint

I created an Angular 5 solution that functions well in both Chrome and Firefox within SharePoint 2013. However, I have run into issues when using IE11. The index.html file was inserted into the SharePoint page using a Content Editor web part. Even after di ...

Can Angular Universal cater to dynamic content needs?

I am considering using Angular Universal for SEO optimization and social media preview purposes. While I understand that it works well with static content, my concern lies with how it handles dynamic content. Specifically, I want search engines and social ...