Search code examples
angulartypescripthttprequestget-request

Populating textarea from DB / ng2


I'm trying to pouplate a textarea with data from my firebase database. I know I should use ngModel, but I'm rather stuck on the syntax.

  <textarea rows="3" cols="35" [(ngModel)]="">  read from db.. </textarea>

In the empty "", i tried writing HttpService.getData(); but that didn't work. I also tried writing http.service.ts.getData() but that didn't work either.

By using the code below, I'm able to get the response outputted to the console, so I should use that somehow ... Could anyone tell me how?

@Injectable()
export class HttpService {

  constructor(private http: Http) { }


  getData() {
   return this.http.get('https://URL-HERE.json').map((response: Response) => response.json());
 }


}

@Component({
  selector: 'message-form',
  templateUrl: './message-form.component.html',
  providers: [HttpService]
})
    export class MessageFormComponent implements OnInit{
 constructor(private httpService: HttpService) { }

  ngOnInit(){

    this.httpService.getData()
      .subscribe(
        (data: any) => console.log(data));

  }

Solution

  • When you get the data, store it in a variable that you can then use in the ngModel:

    data: any = {}; // replace any with the actual type
    
    ngOnInit() {
      this.httpService.getData()
        .subscribe(
          (data: any) => {
            this.data = data;
            console.log(data);
        });
      }
    

    and then:

    <textarea rows="3" cols="35" [(ngModel)]="data">  read from db.. </textarea>