# 创建组件

PS D:\angular\angulardemo05> ng g component components/search

# app.module.ts 引入 form module

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { SearchComponent } from './components/search/search.component';
@NgModule({
  declarations: [
    AppComponent,
    SearchComponent
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

# app.component.html 引入组件标签

<app-search></app-search>

# search.component.html

<div class="search">
    <input type="text" [(ngModel)]="keywords"/> &nbsp;<button (click)="doSearch()">搜索</button>
    <hr>
    <ul>
        <li *ngFor="let item of historyList;let key=index;">
            {{item}}
            <button (click)="deleteHistory(key)">x</button>
        </li>
    </ul>
</div>

# search.component.scss

.search{
    width: 400px;
    margin: 20px auto;
    input{
        margin-bottom: 20px;
        width: 300px;
        height: 32px;
    }
    button{
        height: 32px;
        width: 80px;
    }
}

# search.component.ts

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.scss']
})
export class SearchComponent implements OnInit {
  public keywords:string = ''
  public historyList:any[] = []
  constructor() { }
  ngOnInit(): void {
  }
  doSearch(){
    if (this.historyList.indexOf(this.keywords) == -1){
      this.historyList.push(this.keywords)
    }
    console.log(this.keywords)
    this.keywords = ''
  }
  deleteHistory(key:any){
    console.log(key)
    this.historyList.splice(key, 1)
  }
}