好的,所以我有一個選中標記表單的列表,點擊它們後,我提交一個事件並將所有選中的框值放入一個列表中,然後將該列表與另一個列表進行比較將匹配檢查值從true更改爲false(使用index)。indexOf比較兩個列表,不匹配確切值
當我點擊加拿大,我的控制檯打印預期的輸出(加拿大是真實的,美國和墨西哥是假的), ,但後來我點擊墨西哥,所以現在加拿大和墨西哥已被選中,我所有的國家都轉向假。
我想知道,如果這是我正在implenting指數的方式有問題,或者是它調用導致此功能的順序?一個複選框應該返回true。
組件:
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
@Component({
selector: 'app-geo-drop',
templateUrl: './geo-drop.component.html',
styleUrls: ['./geo-drop.component.css']
})
export class GeoDropComponent implements OnInit {
selectedItems: any [] = [];
places = [
{ code: 'US', allow: 'true', name: 'United States', continent: 'North America' },
{ code: 'CA', allow: 'true', name: 'Canada', continent: 'North America' },
{ code: 'MX', allow: 'false', name: 'Mexico', continent: 'North America' }
];
countriesForm: FormGroup;
constructor() { }
ngOnInit() {
// add checkbox for each country
this.countriesForm = new FormGroup({});
for (let i = 0; i < this.places.length; i++) {
this.countriesForm.addControl(
this.places[i].name, new FormControl(false)
)
}
}
allow(selectedPlaces: Array<any>, allPlaces: Array<any>) {
allPlaces.filter(function (place) {
if (place.name.indexOf(selectedPlaces) > -1) {
place.allow = true;
} else {
place.allow = false;
};
});
this.places.forEach(item => {
console.log(item.name, item.allow);
});
}
search(place, event) {
let index = this.selectedItems.indexOf(place.name);
if (event.target.checked) {
if (index === -1) {
this.selectedItems.push(place.name);
console.log(this.selectedItems);
}
} else {
if (index !== -1) {
this.selectedItems.splice(index, 1);
console.log(this.selectedItems);
}
}
this.allow(this.selectedItems, this.places);
}
}
HTML
<div class="geo-list">
<div class="content-box container">
<form [formGroup]="countriesForm">
<div class="place" *ngFor="let place of places">
<input
type="checkbox"
formControlName="{{place.name}}"
(change)="search(place, $event)"
>
{{ place.name }} | {{ place.code }} | {{ place.continent }}
</div>
</form>
</div>
</div>
我開始想,這可能是因爲我的OnInit函數不會從我的地方列表匹配的當前值的複選框。但是,我的允許函數遍歷並處理它,所以它不應該馬上改變值?或者我應該在我的onInit函數中調用允許函數? – FussinHussin
作爲一個方面說明,也許有一種方法可以直接從表單到地點列表傳遞真假值,反之亦然?像,使框檢查=真,並提交回數據。以及使用正確的檢查來初始化複選框。仍在工作,但任何想法,讓我知道 – FussinHussin
更新我添加[checked] =「{{place.allow}}」更新這個複選框列表。這增加了一些甚至怪異的行爲 – FussinHussin