Nour Mawla
Nour Mawla

Reputation: 351

Angular error TS2531: Object is possibly 'null'

So I have a Component.html that includes an input as follows:

<input type="text" (change) = "setNewUserName($event.target.value)"/>

the component.ts is:

import { Component } from "@angular/core";
@Component({
    selector : 'app-users-list',
    templateUrl : './usersList.component.html'
})
export class UsersListComponent 
{
   setNewUserName (userName : string): void {
       console.log('setNewUserName', userName)
   }
}

and finally the module.ts is:

@NgModule ({
    declarations: [UsersListComponent],
    imports : [CommonModule],
    exports: [UsersListComponent]
})
export class UsersListModule {}

When running the server, the following error pops up:

error TS2531: Object is possibly 'null'.

1 <input type="text" (change) = "setNewUserName($event.target.value)"/>
                                                              ~~~~~

Upvotes: 22

Views: 24538

Answers (3)

mojgan
mojgan

Reputation: 41

this worked for me

($any($event.target).value);

in Angular 13

Upvotes: 4

Barremian
Barremian

Reputation: 31115

Are you using Angular Ivy? Most possibly it's due to the template type checking in Ivy AOT.

Nevertheless, there are multiple options

Option 1: Send the event as argument

<input type="text" (change) = "setNewUserName($event)"/>
export class UsersListComponent {
    setNewUserName(event: Event): void {
      console.log('setNewUserName', (event.target as HTMLTextAreaElement).value);
    }
}

Option 2: Use a template reference variable

<input #userName type="text" (change) = "setNewUserName(userName.value)"/>
export class UsersListComponent {
   setNewUserName (userName : string): void {
       console.log('setNewUserName', userName)
   }
}

Option 3: Disable type checking using $any()

<input type="text" (change) = "setNewUserName($any($event.target).value)"/>
export class UsersListComponent {
   setNewUserName (userName : string): void {
       console.log('setNewUserName', userName)
   }
}

Option 4: Template-driven or reactive form

Use a template-driven or reactive form to get the input value. IMO this would be the most elegant approach.

Update: add disable type checking

Upvotes: 40

Ankit Verma
Ankit Verma

Reputation: 101

try this

setNewUserName($any($event.target).value);

it will work

Upvotes: 8

Related Questions