Uygulamanıza arama özelliği ekleyin

Bu eğitim dersi, Angular uygulamanıza arama işlevselliğinin nasıl ekleneceğini gösterir.

Uygulama, kullanıcıların uygulamanız tarafından sağlanan veriler arasında arama yapmasını ve yalnızca girilen terimle eşleşen sonuçları görüntülemesini sağlayacaktır.

IMPORTANT: Eğitimin bu adımı için yerel ortamınızı kullanmanızı öneriyoruz.

Neler öğreneceksiniz

  • Uygulamanız, eşleşen konut konumlarını aramak için bir formdaki verileri kullanacak
  • Uygulamanız yalnızca eşleşen konut konumlarını görüntüleyecek
  1. Home bileşeninin özelliklerini güncelleyin

    Bu adımda, filtreleme için kullanacağınız yeni bir dizi özelliğinde veri depolamak üzere Home sınıfını güncelleyeceksiniz.

    1. src/app/home/home.ts dosyasında, sınıfa filteredLocationList adında yeni bir özellik ekleyin.

      Add the filteredLocationList property in home.ts

      import {ChangeDetectorRef, Component, inject} from '@angular/core';
      import {HousingLocation} from '../housing-location/housing-location';
      import {HousingLocationInfo} from '../housinglocation';
      import {HousingService} from '../housing.service';
      
      @Component({
        selector: 'app-home',
        imports: [HousingLocation],
        template: `
          <section>
            <form>
              <input type="text" placeholder="Filter by city" #filter />
              <button class="primary" type="button" (click)="filterResults(filter.value)">Search</button>
            </form>
          </section>
          <section class="results">
            @for (housingLocation of filteredLocationList; track $index) {
              <app-housing-location [housingLocation]="housingLocation" />
            }
          </section>
        `,
        styleUrls: ['./home.css'],
      })
      export class Home {
        private readonly changeDetectorRef = inject(ChangeDetectorRef);
        housingLocationList: HousingLocationInfo[] = [];
        housingService: HousingService = inject(HousingService);
        filteredLocationList: HousingLocationInfo[] = [];
      
        constructor() {
          this.housingLocationList = this.housingService.getAllHousingLocations();
          this.filteredLocationList = this.housingLocationList;
        }
      
        filterResults(text: string) {
          if (!text) {
            this.filteredLocationList = this.housingLocationList;
            return;
          }
      
          this.filteredLocationList = this.housingLocationList.filter((housingLocation) =>
            housingLocation?.city.toLowerCase().includes(text.toLowerCase()),
          );
        }
      }
      

      filteredLocationList, kullanıcı tarafından girilen arama kriterlerine uyan değerleri tutar.

    2. filteredLocationList, sayfa yüklendiğinde varsayılan olarak tüm konut konumu değerlerini içermelidir. Home bileşeninin constructor'ını değeri ayarlamak için güncelleyin.

      Set the value of filteredLocationList

      import {ChangeDetectorRef, Component, inject} from '@angular/core';
      import {HousingLocation} from '../housing-location/housing-location';
      import {HousingLocationInfo} from '../housinglocation';
      import {HousingService} from '../housing.service';
      
      @Component({
        selector: 'app-home',
        imports: [HousingLocation],
        template: `
          <section>
            <form>
              <input type="text" placeholder="Filter by city" #filter />
              <button class="primary" type="button" (click)="filterResults(filter.value)">Search</button>
            </form>
          </section>
          <section class="results">
            @for (housingLocation of filteredLocationList; track $index) {
              <app-housing-location [housingLocation]="housingLocation" />
            }
          </section>
        `,
        styleUrls: ['./home.css'],
      })
      export class Home {
        private readonly changeDetectorRef = inject(ChangeDetectorRef);
        housingLocationList: HousingLocationInfo[] = [];
        housingService: HousingService = inject(HousingService);
        filteredLocationList: HousingLocationInfo[] = [];
      
        constructor() {
          this.housingLocationList = this.housingService.getAllHousingLocations();
          this.filteredLocationList = this.housingLocationList;
        }
      
        filterResults(text: string) {
          if (!text) {
            this.filteredLocationList = this.housingLocationList;
            return;
          }
      
          this.filteredLocationList = this.housingLocationList.filter((housingLocation) =>
            housingLocation?.city.toLowerCase().includes(text.toLowerCase()),
          );
        }
      }
      
  2. Home bileşeninin şablonunu güncelleyin

    Home bileşeninde, kullanıcıdan girdi almak için kullanacağınız bir girdi alanı zaten var. Bu dize metin, sonuçları filtrelemek için kullanılacaktır.

    1. Home şablonunu, input öğesinde #filter adında bir şablon değişkeni içerecek şekilde güncelleyin.

      Add a template variable to the input HTML element in home.ts

      import {ChangeDetectorRef, Component, inject} from '@angular/core';
      import {HousingLocation} from '../housing-location/housing-location';
      import {HousingLocationInfo} from '../housinglocation';
      import {HousingService} from '../housing.service';
      
      @Component({
        selector: 'app-home',
        imports: [HousingLocation],
        template: `
          <section>
            <form>
              <input type="text" placeholder="Filter by city" #filter />
              <button class="primary" type="button" (click)="filterResults(filter.value)">Search</button>
            </form>
          </section>
          <section class="results">
            @for (housingLocation of filteredLocationList; track $index) {
              <app-housing-location [housingLocation]="housingLocation" />
            }
          </section>
        `,
        styleUrls: ['./home.css'],
      })
      export class Home {
        private readonly changeDetectorRef = inject(ChangeDetectorRef);
        housingLocationList: HousingLocationInfo[] = [];
        housingService: HousingService = inject(HousingService);
        filteredLocationList: HousingLocationInfo[] = [];
      
        constructor() {
          this.housingLocationList = this.housingService.getAllHousingLocations();
          this.filteredLocationList = this.housingLocationList;
        }
      
        filterResults(text: string) {
          if (!text) {
            this.filteredLocationList = this.housingLocationList;
            return;
          }
      
          this.filteredLocationList = this.housingLocationList.filter((housingLocation) =>
            housingLocation?.city.toLowerCase().includes(text.toLowerCase()),
          );
        }
      }
      

      Bu örnek, input öğesine değeri olarak erişmek için bir şablon referans değişkeni kullanır.

    2. Ardından, "Search" düğmesine bir olay işleyici eklemek için bileşen şablonunu güncelleyin.

      Bind the button click event to a method in home.ts

      import {ChangeDetectorRef, Component, inject} from '@angular/core';
      import {HousingLocation} from '../housing-location/housing-location';
      import {HousingLocationInfo} from '../housinglocation';
      import {HousingService} from '../housing.service';
      
      @Component({
        selector: 'app-home',
        imports: [HousingLocation],
        template: `
          <section>
            <form>
              <input type="text" placeholder="Filter by city" #filter />
              <button class="primary" type="button" (click)="filterResults(filter.value)">Search</button>
            </form>
          </section>
          <section class="results">
            @for (housingLocation of filteredLocationList; track $index) {
              <app-housing-location [housingLocation]="housingLocation" />
            }
          </section>
        `,
        styleUrls: ['./home.css'],
      })
      export class Home {
        private readonly changeDetectorRef = inject(ChangeDetectorRef);
        housingLocationList: HousingLocationInfo[] = [];
        housingService: HousingService = inject(HousingService);
        filteredLocationList: HousingLocationInfo[] = [];
      
        constructor() {
          this.housingLocationList = this.housingService.getAllHousingLocations();
          this.filteredLocationList = this.housingLocationList;
        }
      
        filterResults(text: string) {
          if (!text) {
            this.filteredLocationList = this.housingLocationList;
            return;
          }
      
          this.filteredLocationList = this.housingLocationList.filter((housingLocation) =>
            housingLocation?.city.toLowerCase().includes(text.toLowerCase()),
          );
        }
      }
      

      button öğesindeki click olayına bağlanarak, filterResults fonksiyonunu çağırabilirsiniz. Fonksiyonun argümanı, filter şablon değişkeninin value özelliğidir. Özellikle, input HTML öğesinden gelen .value özelliğidir.

    3. Son şablon güncellemesi @for yönergesi içindir. @for yönergesini filteredLocationList dizisindeki değerler üzerinde yineleme yapacak şekilde güncelleyin.

      Update the @for template directive in home.ts

      import {ChangeDetectorRef, Component, inject} from '@angular/core';
      import {HousingLocation} from '../housing-location/housing-location';
      import {HousingLocationInfo} from '../housinglocation';
      import {HousingService} from '../housing.service';
      
      @Component({
        selector: 'app-home',
        imports: [HousingLocation],
        template: `
          <section>
            <form>
              <input type="text" placeholder="Filter by city" #filter />
              <button class="primary" type="button" (click)="filterResults(filter.value)">Search</button>
            </form>
          </section>
          <section class="results">
            @for (housingLocation of filteredLocationList; track $index) {
              <app-housing-location [housingLocation]="housingLocation" />
            }
          </section>
        `,
        styleUrls: ['./home.css'],
      })
      export class Home {
        private readonly changeDetectorRef = inject(ChangeDetectorRef);
        housingLocationList: HousingLocationInfo[] = [];
        housingService: HousingService = inject(HousingService);
        filteredLocationList: HousingLocationInfo[] = [];
      
        constructor() {
          this.housingLocationList = this.housingService.getAllHousingLocations();
          this.filteredLocationList = this.housingLocationList;
        }
      
        filterResults(text: string) {
          if (!text) {
            this.filteredLocationList = this.housingLocationList;
            return;
          }
      
          this.filteredLocationList = this.housingLocationList.filter((housingLocation) =>
            housingLocation?.city.toLowerCase().includes(text.toLowerCase()),
          );
        }
      }
      
  3. Olay işleyici fonksiyonunu uygulayın

    Şablon, filterResults fonksiyonunu click olayına bağlamak için güncellendi. Sıradaki göreviniz, Home sınıfında filterResults fonksiyonunu uygulamaktır.

    1. Home sınıfını filterResults fonksiyonunun uygulamasını içerecek şekilde güncelleyin.

      Add the filterResults function implementation

      import {ChangeDetectorRef, Component, inject} from '@angular/core';
      import {HousingLocation} from '../housing-location/housing-location';
      import {HousingLocationInfo} from '../housinglocation';
      import {HousingService} from '../housing.service';
      
      @Component({
        selector: 'app-home',
        imports: [HousingLocation],
        template: `
          <section>
            <form>
              <input type="text" placeholder="Filter by city" #filter />
              <button class="primary" type="button" (click)="filterResults(filter.value)">Search</button>
            </form>
          </section>
          <section class="results">
            @for (housingLocation of filteredLocationList; track $index) {
              <app-housing-location [housingLocation]="housingLocation" />
            }
          </section>
        `,
        styleUrls: ['./home.css'],
      })
      export class Home {
        private readonly changeDetectorRef = inject(ChangeDetectorRef);
        housingLocationList: HousingLocationInfo[] = [];
        housingService: HousingService = inject(HousingService);
        filteredLocationList: HousingLocationInfo[] = [];
      
        constructor() {
          this.housingLocationList = this.housingService.getAllHousingLocations();
          this.filteredLocationList = this.housingLocationList;
        }
      
        filterResults(text: string) {
          if (!text) {
            this.filteredLocationList = this.housingLocationList;
            return;
          }
      
          this.filteredLocationList = this.housingLocationList.filter((housingLocation) =>
            housingLocation?.city.toLowerCase().includes(text.toLowerCase()),
          );
        }
      }
      

      Bu fonksiyon, text parametresinin değerini housingLocation.city özelliğiyle karşılaştırmak için String filter fonksiyonunu kullanır. Eğlenceli bir alıştırma olarak bu fonksiyonu herhangi bir özellik veya birden fazla özellikle eşleşecek şekilde güncelleyebilirsiniz.

    2. Kodunuzu kaydedin.

    3. Tarayıcıyı yenileyin ve metin girdikten sonra "Search" düğmesine tıkladığınızda konut konumu verilerini şehre göre arayabildiğinizi doğrulayın.

      filtered search results based on user input

SUMMARY: Bu derste, şablon değerleriyle etkileşim kurmak için şablon değişkenleri kullanmak üzere uygulamanızı güncellediniz ve olay bağlama ile dizi fonksiyonları kullanarak arama işlevselliği eklediniz.

Bu derste ele alınan konular hakkında daha fazla bilgi için: