angular cant find toggle function in model

293 Views Asked by At

I am binding data in model class and looping the data fine. But I failed to bind toggle function in model class to the template click event.

I created a model to bind the data from a jokelist component and looping the jokes with ngFor directive. Created jokerow component and send joke object as input param from jokelist. the properties are working fine. but the function is not detected.

Model:

export interface IJoke {
    fname: string;
    lname: string;
    hide: boolean;    
}

export interface IJokelist {
    jokeList: IJoke[];
}

export class JokeModel {
    jokeList: IJokelist;
    joke: IJoke;
    hide: boolean;

    constructor(jokeList: IJokelist) {
        this.jokeList = jokeList;
        // this.hide = true;
    }

    getAllProducts(): any {
        return this.jokeList;
    }

    toggle(): void {
        //this.hide = !this.hide;
        console.log('hi');
    }
}

jokelist.Component.ts

export class JokelistComponent implements OnInit {

  jokesList: IJokelist;

  jokesStatic: any = [{ fname: 'chandu', lname: 'm', hide: true },
  { fname: 'venkat', lname: 'p', hide: true },
  { fname: 'ramu', lname: 'b', hide: true }];


  constructor() {
    const newProduct = new JokeModel(this.jokesStatic);
    this.jokesList = newProduct.getAllProducts();
  }

  ngOnInit() {
  }
}

jokelist.component.html

<app-jokerow *ngFor="let j of jokesList" [joke]="j"></app-jokerow>

jokerow component

export class JokerowComponent implements OnInit {
  @Input('joke') data: IJoke;

  constructor() { }

  ngOnInit() {
  }

}

jokerow.component.html

<div class="card card-block">
    <h4 class="card-title">{{data.fname}}</h4>     
    <p class="card-text"
     [hidden]="data.hide">{{data.lname}}</p>
  <a (click)="data.toggle()"
     class="btn btn-warning">Tell Me
  </a>
</div>
2

There are 2 best solutions below

7
Dheeraj Kumar On BEST ANSWER

toggle function is not specific to your model.

You have to pass data to toggle and then you can show/hide.

<a (click)="toggle(data)"
     class="btn btn-warning">Tell Me
  </a>

In component,

 toggle(data): void {
        data.hide = !data.hide;   //updated
        console.log('hi');
    }

Hope this helps.

3
Muhammed Albarmavi On

Update getAllProducts so jokesList elements will have toggle function

getAllProducts(): any {
    return this.jokeList.map (j => { 
        j.toggle = this.toggle;
        return j;
    });
}