Angular 5 - How to use a custom function within a class

Discussão em 'Angular' iniciado por Kay, Outubro 18, 2024.

  1. Kay

    Kay Guest

    I created a comment class, so i that i can refactor some code and add custom functions within the classes rather than having them all in my component. For example, a function for toggling Like/Dislike of a comment. However, when i create a simple custom function "hello" it does not work.

    In my moment.component.ts i have a service which retrieves a "moment" object from my backend. I then use an ngFor in my app-moment-comment component to display each comment by passing in the current comment object. Here the moment is set to type any;

    moment.component.ts

    <app-moment-comment [comment]="comment" class="comment" *ngFor="let comment of moment?.comments></app-moment-comment>


    comment.component.ts

    export class MomentCommentComponent implements OnInit {

    @Input() comment: Comment

    constructor() { }

    ngOnInit() {

    this.comment.hello();

    }


    comment.model.ts

    export class Comment {

    _id: any;
    body: any;
    moment: any;
    author: any;
    likes: any;
    dislikes: any;
    parent: any;
    replies: any;

    constructor() {
    console.log(this);
    }


    hello() {
    console.log("hello")
    }



    }


    When i call the hello() method, i get an error saying:


    ERROR TypeError: this.comment.hello is not a function
    ​

    Continue reading...

Compartilhe esta Página