Non-responding function in one way binding

时间:2019-04-08 13:16:01

标签: html angular typescript

The problem may be simple, but I do not see what's wrong right now.

Within the service in my Angular project there is the following function:

  public addCompany(){
    let newP:any ={
      "name": "Chay elsarici",
      "password": "1234",
      "email": "chay@touoors.com",
      "coupons": []
      }

     this.myHttpClient.post<any>("http://localhost:8080/CouponSystemJersey/couponsystem/admin/insertCompany", newP).subscribe(
       (res)=>{console.log("new company")},
       (err)=>{console.log(err)}
     ); 
  }

In the html file of the Componente admin has the following button:

<input type="button" onclick="addNewCompany()" value="Click here to insert company "/> 

And in the file ts of the component admin existing following function:

   public addNewCompany():void{
    console.log("someone click");
    this.myService.addCompany();
    };

When I click the button I get the following error:

Uncaught ReferenceError: addNewCompany is not defined
    at HTMLInputElement.onclick (admin:13)

what am I missing?

2 个答案:

答案 0 :(得分:3)

In your HTML you're using

onclick="addNewCompany()"

You have to use

(click)="addNewCompany()"

When you use onclick you're using the default HTML definition and this will look at the global JavaScript scope. If you use (click) the function will run in the scope of your component's controller.

More info

答案 1 :(得分:0)

This error indicates that your Component doesn't know the Service which provides the addCompany() method.

Are you importing well your Service into the Component's constructor?

Are you also declaring it in your Component's Module providers array?

I guess you may know how to do, but here are the dedicated topics in the Angular documentation:

As said by @Giovani Vercauteren, Angular as its own implementation of onclick with the (click)="..." binding. So you must change it in your code.