4

I have a URL like this one:

https://example.com/?username1=Dr&Organization=Pepper&action=create

I need to display it on my browser inside a text box.

<input type="text" name="varname" value="Dr">

I need to get Dr in my textbox

3
  • <input type="text" name="varname" value="https://example.com/?username1=Dr&Organization=Pepper&action=create">? Commented Jan 19, 2018 at 20:17
  • What version of Angular are you using? Commented Jan 19, 2018 at 20:19
  • We are using Angular 2.0 Commented Jan 19, 2018 at 20:22

1 Answer 1

2

I'm presuming your url endpoint returns JSON and your attempting to use the returned data to populate your input value.

Firstly import the HttpClientModule in your module dependencies:

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Then from within your foo.component.ts you can inject an instance of HttpClient in the constructor.

constructor(private http: HttpClient){
  }

Then you can use said HttpClient instance http like so:

this.http.get('https://example.com/?username1=Dr&Organization=Pepper&action=create').subscribe(data => {
      console.log(data);
    });
  }

This can then be put into a property (myProp) which can be referenced like so:

<input *ngIf="myProp" type="text" name="varname" value="myProp">

Note that we use *ngIF to make sure that our property isn't loaded until myProp is not null or undefined.


Main App component - app-root

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'app';
  name = null;


  constructor(private http: HttpClient){
  }

  ngOnInit(): void {
    this.http.get('https://example.com/?username1=Dr&Organization=Pepper&action=create').subscribe(data => {
    // data = result: {name: 'Derek da Doctor'}
      this.name = data.result.name;
    });
  }
}

app.component.html

<input *ngIf="name" type="text" name="varname" value="{{name}}">
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.