如何在使用Angular6+将记录插入数组期间防止重复值
**PARENTCOMPONENT.HTML:**
<div class="form-group" style="margin-left:30px;margin-top:30px;">
<input type="text" class="form-control" placeholder="Posts" name="post" [(ngModel)]="post" #clearText>
</div>
<button type="submit" class="btn btn-sm btn-primary" (click)="AddServer(post)"
style="margin-left:30px;margin-top:10px;" (blur) = "clearText.value = ''">Click</button>
<app-child [childPost]="parentPosts"></app-child>
**PARENTCOMPONENT.TS:**
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-parent',
templateUrl: './parent.component.html',
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
post = '';
parentPosts: any[] = [];
constructor() { }
ngOnInit() {
}
AddServer(post)
{
this.parentPosts.push(post);
console.log(post);
}
}
**CHILDCOMPONENT.HTML:**
<div style="margin-left: 30px; margin-top:10px;" *ngFor="let p of childPost">
<p>{{p}}</p>
</div>
**CHILDCOMPONENT.TS:**
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
@Input() childPost: any[] = [];
constructor() { }
ngOnInit() {
}
}
嗨,伙计们,上面代码是用文本框值和parencomponent中的按钮将数据从父组件插入到子组件。TS代码我需要的是在将值推入数组的过程中,值必须是唯一的,如果我发布重复的值,它会抛出一个警告或错误消息,值已经这样插入了,所以请帮助我解决这个问题。。。。
您可以使用Set data结构来省略重复的插入,这比使用一个额外的循环来验证它是否已经在数组中,然后省略它要好得多。
parentPosts: Set = new Set();
// then use it like
this.parentPosts.add(post); // if post already exists it'll just not add it