Búsqueda de sitios web

angular - ¿Cómo obtener el valor de ngModel de una etiqueta input en un componente en angularjs4?


Soy nuevo en angularjs4. Estoy trabajando con angular-cli. Aquí necesito obtener el valor de un ngModel de una etiqueta input en mi componente. ¿Cómo puedo obtener ese valor ingresado en el campo de entrada? Usando ese valor necesito escribir un filtro para mostrar los datos buscados en mi página. ¿Cómo puedo implementar esto en angular4? Aquí están mis archivos app.component.html y app.component.ts:

import {
    Component
} from '@angular/core';
import {
    Http,
    Response,
    Headers,
    RequestOptions
} from '@angular/http';
import 'rxjs/add/operator/map';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    productsList = '';
    show: boolean;
    hide: boolean;
    listBtn: boolean;
    gridBtn: boolean;
    values = '';

    onKey(event: any) { // without type info
        this.values += event.target.value;
        console.log("value " + this.values);
    }
    listView() {
        this.gridBtn = true;
        this.show = true;
        this.hide = false;
        this.listBtn = false;
    }
    gridView() {
        this.listBtn = true;
        this.gridBtn = false;
        this.show = false;
        this.hide = true;

    }
    constructor(private http: Http) {
        this.show = false;
        this.hide = true;
        this.show = false;
        this.listBtn = true;
        this.gridBtn = false;
        this.getData();
    }
    createAuthorizationHeader(headers: Headers) {
        headers.append('Authorization', 'Basic ' +
            btoa('ck_543700d9f8c08268d75d3efefb302df4fad70a8f:cs_f1514261bbe154d662eb5053880d40518367c901'));
        headers.append("Content-Type", "application/x-www-form-urlencoded");
    }
    getData() {
        console.log('hellooo');
        let headers = new Headers();
        this.createAuthorizationHeader(headers);
        return this.http.get(' https://www.colourssoftware.com/wordpress/wp-json/wc/v2/products', {
            headers: headers
        })
            .subscribe(res => {
                const products = res.json();
                console.log(products);
                this.productsList = products;
                console.log(this.productsList);
            })


    }

}

HTML

<div class="container" align="center">
    <div class="row">
        <div class="col-sm-6 col-sm-offset-3">
            <div class="input-group stylish-input-group">
                <input type="text" class="form-control" placeholder="Let's find your product....." (keyup)="onKey($event)">
                <span class="input-group-addon">
                    <button type="submit">
                        <span class="glyphicon glyphicon-search"></span>
                    </button>
                </span>
            </div>
        </div>
    </div>
    <br>
</div>


<br>
<div *ngIf="show">
    <ul class="list-group">
        <li class="list-group-item" *ngFor="let data of productsList">
            <img src="{{data.images[0].src}}" alt="image" width="auto" height="200px">
            <span>{{data.name}}</span>
            <span>{{data.regular_price}}</span>
        </li>
    </ul>
</div>

Respuesta #1

1. Si quieres vinculacion de datos unidireccional (del Componente al HTML), usa -

<input [ngModel]="variable">

2. Si quieres enlace de datos bidireccional (del Componente al HTML y viceversa), utiliza -

<input [(ngModel)]="variable">

3. Si quieres trabajar con los datos cambiados en un campo de entrada en HTML mientras trabajas con enlazado de datos unidireccional, tienes que usar (ngModelChange) como se muestra a continuación :

<input [ngModel]="variable"(ngModelChange)="function_to_fire_on_model_change($event)">

Respuesta #2

ACTUALIZACIÓN:

Si quieres obtener el valor de entrada, pero sin ngModel (como en tu fragmento no lo usas), puedes obtenerlo así:

 <input type="text" #input class="form-control" placeholder="Let's find your product....." (keyup)="onKey($event, input.value)">

onKey(event, newValue){
  console.log(newValue);
  console.log(event.key)
}


Normalmente, el patrón sería:

HTML

<input [(ngModel)]="yourModel" ....> 

o

<input [ngModel]="yourModel" (ngModelChange)="doSomething($event)"....> 

Typescript:

yourModel:any;
....
doSomething(event){
   console.log(event) // input value is logged
}

Aquí, cualquier cambio en la entrada actualizará el ngModel ya que está vinculado de manera bidireccional.

  • Documentación de Angular

Artículos relacionados