angular - 使用可移除的輸入/標籤進行搜尋(Ionic 2)
我正在創建一個食譜應用程式,其中有一個搜尋功能,用戶可以按食材來搜尋。我希望功能是當他們按下空格鍵來輸入下一個內容時,它會以標籤的形式顯示在下方,並在旁邊有一個 X,從而取消選擇相關的輸入。
我目前的搜尋看起來像
但目標是讓它看起來像標籤在下面一樣。
由於這是針對 Ionic 2 應用程式,有人之前見過這樣做或者有教學嗎?或者想要給我一些幫助,那就太好了。
新:剛注意到頁面底部的 Stack Overflow “標籤” 部分正是我想要的實現方式
答案#1
你可以在這個 Plunker 中找到類似的東西。還有很多改進的空間(以及一些更多的驗證),但這個示範基本上就是你所尋找的。
這段程式碼非常簡單,最相關的部分是:
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
...
...
})
export class HomePage {
public myForm: FormGroup;
public tags: Array<string>;
constructor(public formBuilder: FormBuilder) {
this.tags = ['tag1', 'tag2', 'tag3'];
this.myForm = this.formBuilder.group({
tags: ['']
});
// Add an async validation for the username
this.myForm.get('tags')
.valueChanges
.subscribe((value: string) => {
if(value.indexOf(' ') > -1) {
let newTag = value.split(' ')[0];
console.log(newTag);
if(newTag) {
this.tags.push(newTag);
this.myForm.get('tags').setValue('');
}
}
});
}
public deleteTag(tagName: string) {
// Find the index of the tag
let index = this.tags.indexOf(tagName);
// Delete the tag in that index
this.tags.splice(index, 1);
}
}
然後在視圖中:
<ion-header>
<ion-navbar>
<ion-title>HomePage</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<form [formGroup]="myForm">
<ion-item>
<ion-input formControlName="tags" type="text"></ion-input>
</ion-item>
</form>
<div class="tag-container">
<span class="tag" *ngFor="let tag of tags">
{{ tag }}
<ion-icon name="close" (click)="deleteTag(tag)"></ion-icon>
</span>
</div>
</ion-content>
最後但同樣重要的是,CSS!
.tag-container {
border: 1px solid #ccc;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
padding: 10px;
margin: 10px;
}
.tag {
display: inline-block;
background-color: #5bc0de;
color: #fff;
margin: 5px 5px;
padding: 2px 5px;
}
答案#2
我會從資料模型的角度來處理這個問題。當你將你想要的東西縮小到核心時,你希望得到的東西是,對於搜索欄中的每個輸入事件,
- 你將搜尋詞轉換成一個單詞陣列
- 你從那個陣列中剝掉最後一個字,並將其作為你的標籤陣列
- 你取陣列中的最後一個字,並把它作為輸入的值
所以,假設你的元件就像
@Component({
.....
template: `
<input [formControl]="searchControl" (input)="onSearchInput(input.value)" />
<label *ngFor="let label of labels">{{ label }} </label>
`
})
export class SearchComponent {
searchControl = new FormControl('');
labels: string[] = [];
onSearchInput(searchValue) {
let newSearchValues: string[] = searchValue.split(' ');
// if the current search term has a space,
// create the new label and update the input field
if (newSearchValues.length > 1) {
this.labels.push(newSearchValues[0]);
this.searchControl.setValue(newSearchValues[1]);
}
}
}
所以,你將搜尋輸入綁定到來自 @angular/forms 套件的 FormControl,以便在需要時可以程式化地設定值(此外還可以利用 FormsModule 中的其他好處,你需要匯入它)。你還想監聽搜尋輸入欄位的輸入事件,並在每個事件發生時,更新你的標籤並根據需要更新輸入欄位。
以上可以幫你入門。可能需要額外的邏輯來處理邊緣情況,可能需要根據需要加入防抖,但至少這可以啟發你的思考。

