Search code examples
angularfunctionoutput

show output from component.ts


I want to print the output generated by the component.ts, but I don't want a console.log, but the returned value on the component-html.

This is my component.html (only the final part):

<div class="col-md-12 pt-2">
     <button type="button" class="btn btn-success btn-sm" (click)="addField()">Add TTP</button>
     <button type="submit" class="btn btn-outline-primary" [disabled]="!ttp_form.valid">Submit</button>
//the call of onSubmit() is done by the formGroup tag at the beginning
    </div>

This is the component.ts:

onSubmit() {      

   //return the data
    this.firebase.getData(this.url)
    .subscribe((data: any) =>{
      this.ttp_db = Object.keys(data).map((key)=> {return data[key]})
      this.ttp_field = Object.keys(this.ttp_form.value).map((key)=> {return this.ttp_form.value[key]})
      this.appartenenza(this.ttp_field, this.ttp_db) --> this is the function that I want to return the value
    })
  }

a little part of the function appartenenza:

appartenenza(ttp_field: any, ttp_db: any) {
    const massimo = Math.max(...punteggi);

if (massimo === 0) {
    return "Nessuna stringa in comune";
  }

const indice = punteggi.indexOf(massimo);

  return console.log("Gruppo con più affinità: ", this.ttp_db[0][indice]); --> I put console log to see the output on the console for test the programm
}

Solution

  • You need to store the returned value in a property, and then use databinding in your template to display it. Make sure you always return a string and don't return the console.log function.

    myValue = '';
    
    onSubmit() {      
       //return the data
       this.firebase.getData(this.url)
        .subscribe((data: any) =>{
          this.ttp_db = Object.keys(data).map((key)=> {return data[key]})
          this.ttp_field = Object.keys(this.ttp_form.value).map((key)=> {return this.ttp_form.value[key]})
          this.myValue = this.appartenenza(this.ttp_field, this.ttp_db);
        })
    }
    
    appartenenza(ttp_field: any, ttp_db: any) {
        const massimo = Math.max(...punteggi);
    
      if (massimo === 0) {
        return "Nessuna stringa in comune";
      }
    
      const indice = punteggi.indexOf(massimo);
    
      return "Gruppo con più affinità: " + this.ttp_db[0][indice];
    }
    

    In your template

    <p>My Value: {{ myValue }}</p>