如何使用ng-multiselect-dropdown将选择选项设置为默认的角度选择?

时间:2019-12-02 10:28:52

标签: javascript html angular web mean-stack

所以在这里,我要从数据库中获取数据并将其存储到事件数组中。此事件数组数据使用ng-multiselect-dropdown显示在book-ticket.component.html上。从这里开始选择一个选项,此数据对应于此event中存储的选定项目。
我正在将ID从另一个组件传递到book-ticket.component,在这里我们使用

接收到它
1

票务组件的HTML部分是

this.idByAllEvents = this.activatedRoute.snapshot.params.id;
票务组件的

.ts部分是

 <div class="form-group">
            <label>Event</label>
            <ng-multiselect-dropdown [placeholder]="'Select the Event'" [data]="this.events" name="event"
                [(ngModel)]="this.event" [settings]="dropdownSettings1">
            </ng-multiselect-dropdown>
        </div>

我希望默认情况下在HTML页面上选择与this.idByAllEvents相对应的选项。但是下拉列表显示了this.events的所有选项。

我尝试使用功能JustExecute设置selectedItem,但是export class BookTicketComponent implements OnInit { user:User; event:Event; offer:Offer; // offer:string; // event:string; idByAllEvents: string; // This is coming from all events page price:number; percentageReduce:number; offers:Offer[]; events:Event[]; dropdownSettings1: IDropdownSettings; dropdownSettings2: IDropdownSettings; selectedItem: any[]; constructor(private Userservice:UserService,private Offerservice:OfferService, private Eventservice:EventService, private router:Router, private activatedRoute:ActivatedRoute) { this.idByAllEvents = this.activatedRoute.snapshot.params.id; console.log(this.idByAllEvents); this.user = new User(); // this.offer = new Offer(); // this.event = new Event(); // this.offer = new Offer(); // this.event = new Event(); this.selectedItem = []; } ngOnInit() { this.dropdownSettings1 = { singleSelection: true, idField: '_id', textField: 'name', selectAllText: 'Select All', unSelectAllText: 'UnSelect All', itemsShowLimit: 3, allowSearchFilter: true, closeDropDownOnSelection: true, }; this.Eventservice.GetEvents().subscribe(res => { this.events = res; this.justExecute(); this.Offerservice.GetOffers().subscribe(res => { this.offers = res }) }); justExecute(){ console.log(this.idByAllEvents); console.log(this.events); for (let index = 0; index < this.events.length; index++) { const element = this.events[index]._id; console.log(element); if(element == this.idByAllEvents){ this.selectedItem.push(this.events[element]); // this.selectedItem = this.events[element] } } console.log(this.selectedItem); } } SaveData(form:NgForm) { if(form.valid) {...} } } 给出了未定义的数组。 如果我们在selectedItem中获得了与idByAllEvents对应的值,那么我们可以在HTML页面上使用console.log(this.selectedItem)来选择该值。

我们应该如何做到这一点。 还有其他方法可以做到这一点。

1 个答案:

答案 0 :(得分:0)

如果 ng-multiselect-dropdown 用于响应式形式的 FormGroup,请确保包含 [ngModelOptions]='{standalone: true}'