angulareventsmodel-driven

angular cant find toggle function in model


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>

Solution

  • 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.