Issue: Unable to assign value to 'googleUri' property of null. Resolving with Interface for two-way binding?

Can anyone help me figure out why I keep getting a 'set property of null' error while attempting 2way binding in my interface?

Whenever I submit the form and trigger the onSave function, I encounter the error "Cannot set property 'googleUri' of null". The console indicates that it's outputting null. How can I resolve this issue while still utilizing my interface?

This is the structure of my interface

export interface User {
    googleUri?: string;
}

This is how my component HTML looks like

<form name="form" (ngSubmit)="onSave()" #f="ngForm" novalidate>
            <div class="row">
              <div class="col-md-12">
                <div class="form-group">
                  <label for="googleUri">Google Excel Address</label>
                  <input type="text" class="form-control form-control-lg" name="googleUri" id="googleUri" [ngModel]="user?.googleUri" (ngModelChange)="user.googleUri=$event"/>
                </div>
              </div>
            </div>
</form>

This is the TypeScript code for my component

export class ProfileComponent implements OnInit {
  private user: User = {};
  public loading: boolean = false;

  constructor(private userService: UserService) { }

  ngOnInit() {
  }

  private onSave(): void {
    console.log(this.user);
    this.userService.saveUserSettings(this.user)
      .subscribe(
        data => console.log(data),
        err => console.log(err),
        () => this.loading = false
      );
  }
}

Answer №1

To achieve two-way data binding, simply utilize [(ngModel)]
Replace your current code with the following:

<input type="text" name="googleUri" id="googleUri" [(ngModel)]="user.googleUri"/>

I have implemented the same example you mentioned and successfully accessed
the googleUri variable within the component.

Make sure to confirm the following:

Have you correctly imported the User interface in the component?

For a demo of this example, click here. Demo

Hopefully, this solution proves beneficial to you. You can view the result image below:

https://i.sstatic.net/DEnfF.png

Answer №2

Modify the access modifier from private to 'public' for the user object.

public user: User = {};

To display the model object in the template, use the pre tag.

<pre>
{{user | json}}
</pre>

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

A guide to submitting forms within Stepper components in Angular 4 Material

Struggling to figure out how to submit form data within the Angular Material stepper? I've been referencing the example on the angular material website here, but haven't found a solution through my own research. <mat-horizontal-stepper [linea ...

Unable to find solutions for all parameters in AnalysisComponent: ([object Object], ?, ?, [

As a newcomer to the Angular framework, I encountered an issue when adding project services. Error: Can't resolve all parameters for AnalysisComponent: ([object Object], ?, ?, [object Object], [object Object], [object Object], [object Object], [obj ...

Tips for validating Angular form group input depending on the value of another input within the form?

I am facing an issue with form validation in my Angular version 8 application. I need to validate a form based on the following rules: If a file is uploaded (even if just clicking the button without selecting a file), then the Reason input is not required ...

Merging multiple observables with RxJs forkJoin

UPDATE : I'm currently facing a challenging issue that I can't seem to resolve. Within my code, there is a list of objects where I need to execute 3 requests sequentially for each object, but these requests can run in parallel for different obje ...

The Angular translation service may encounter issues when used on different routes within the application

I'm currently working on an Angular application that has multi-language support. To better organize my project, I decided to separate the admin routes from the app.module.ts file and place them in a separate file. However, after doing this, I encounte ...

Guide on associating an array of object keys with an array of their corresponding values within a specified object

const obj = { wheels: 4, lights: 2, doors: 4 } customMapFunction(obj, { properties: ["wheels", "lights"], formatter: (wheels, lights) => `${wheels}-${lights}` // "4-2" }) How do I define the types for customMapFunction in TypeScript to ensure th ...

typescript challenging syntax within mix-ins

type Constructor<T> = new (...args: any[]) => T; function f1<T extends {}>(naked: Constructor<T>): any { return class dressed extends naked { } // error } function f2<T extends Constructor<{}>>(naked: T): any { re ...

Encountering an error with Angular2 when referencing node modules

I encountered an issue when trying to use angular2 from the node_modules directory. Can anyone guide me on how to resolve this error? Is there something specific I need to include in my HTML file? I am looking for a Git repository where I can access Angu ...

Is it possible to have routing only within child components in Angular 2?

I have set up a main component as the root component <tracker-module></tracker-module> Within the main component, there are sub-components structured like this: <header></header> <left-navigation></left-navigatio ...

Typescript i18next does not meet the requirement of 'string | TemplateStringsArray NextJS'

While attempting to type an array of objects for translation with i18next, I encountered the following error message in the variable navItems when declaring i18next to iterate through the array Type 'NavItemProps[]' does not satisfy the constrain ...

Changing the background color of .pane and .view elements in an Ionic web application using JavaScript

Looking to modify the background-color of two css selectors, .pane and .view, that are located within the ionic.css file. Despite multiple attempts to do so using JavaScript directly in the index.html file, the changes are not reflected. The code snippet ...

Unexpected behavior with Angular Material's date validation functionality

Currently, I am working on a project involving the mat-datepicker component. The functionality allows users to enter a value and select a date using my code, which is functioning correctly. One key feature of this project is an update button that is initia ...

Incorporate matTooltip dynamically into text for targeted keywords

I'm currently tackling a challenge in my personal Angular project that utilizes Angular Material. I'm struggling to find a solution for the following issue: For instance, I have a lengthy text passage like this: When you take the Dodge action, ...

Error message in Angular 6: Unable to bind to 'org' as it is not recognized as a valid property of 'appCycleDirection' (Directive)

Here is the code snippet of a directive I have created: import { Directive, Input, OnInit } from '@angular/core'; import {GoogleMapsAPIWrapper} from '@agm/core'; declare let google: any; @Directive({ // tslint:disable-next-line:dire ...

`I'm having difficulty transferring the project to Typescript paths`

I posted a question earlier today about using paths in TypeScript. Now I'm attempting to apply this specific project utilizing that method. My first step is cloning it: git clone <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cf ...

`How can I troubleshoot an Angular project's *ngIf structural directive using Chrome?`

Seeking a way to include Angular source code and source map into my Angular CLI project for easier debugging of directives such as *ngIf in Chrome. Is there a method to attach a debugger to ng_if.ts using configuration in angular.json or by adding a sourc ...

Navigating to view component in Angular2 Routing: Issue with router-link click event not working

I have set up my app.routes.ts file and imported all the necessary dependencies. Afterward, I connected all the routes to their respective Components as follows: import {ModuleWithProviders} from '@angular/core'; import {Routes, RouterModule} f ...

mongodb is experiencing issues with the findOneAndUpdate operation

Below is the code snippet for updating the database. let profileUrl = 'example' UserSchemaModel.findOneAndUpdate({_id:userId}, {$set: {profileUrl:profileUrl} }, {new:true}) .then((updatedUser:UserModel) => { console.log(updatedUser.profil ...

Encountering an unexpected closing tag "a" while using Angular 2 with webpack

I am currently working with an Angular 2 template that displays tabs on my website: <div id="menu"> <ul id="tabs"> <li *ngFor="let tab of tabs; let i = index" [class.active]="selectedTab===i"> <a routerLink="/p ...

Make the angular component refresh when the back button is pressed

I am working on a TeamSeasonComponent with the URL http://localhost:4200/teams/season/<team_id>. On this page, there are links to other team's pages which would take me to http://localhost:4200/teams/season/team_2_id>. I switch between these ...