我正在创建一个食谱应用程序,我可以在其中进行搜索,用户可以按成分进行搜索。我希望功能是当他们触摸空格键键入下一个输入时,它会显示为下面的标签,旁边有一个 X,因此取消选择相关输入。
由于这是针对 Ionic 2 应用程序的,有没有人以前看过这个程序或教程?或者想给我一些帮助,那就太好了。
新:刚刚注意到页面底部的 Stack overflow“标签”部分正是我希望实现的方式
最佳答案
您可以在 this plunker 中找到类似的内容.有很大的改进空间(以及更多验证),但该演示正是您正在寻找的。p>
代码非常简单,最相关的部分是:
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);
}
}
然后在 View 中:
<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;
}
关于angular - 使用可移动输入/标签搜索 (Ionic 2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42700433/