简体   繁体   中英

Angular 2 Bind Selected Attribute to Dynamically Created Options

I'm using Angular 2 RC4.

I create a dropdown select element which is bound to a variable in my component and create the options for this select using *ngFor , like this:

<select id="role-select" class="form-control" [(ngModel)]="foo.bars" multiple>
    <option *ngFor="let bar of bars">{{bars}}</option>
</select>

The bars variable is dynamically populated:

ngOnInit(){
    this._service.GetBars().subscribe(
        result => {
            this.bars = result;
        },
        err => {
            console.log(err);
        },
        () => {}  
    );
}

I also dynamically populate the foo.bars variable:

constructor(public _service: Service){
    _service.GetFooBars()
        .subscribe((data) => {
            this.foo.bars = data;
        },(err) => {
            console.log(err);
        },  () => {
            // done                    
        });
}

Now what I want to do is to set the selected attribute to true on any options that match the bars in foo.bars . Currently I use this:

var roleSelect = document.getElementById("role-select");
this.foo.bars.forEach((v,i) => {
    for (var j = 0; j < roleSelect.options.length; j++) {
        if (roleSelect.options[j].text === v) {
            roleSelect.options[j].selected = true;
        }
    }
});

This works perfectly fine, but the transpiler throws errors saying options does not exist on HTMLElement[] and I would like a slightly more robust solution.

Any idea is appreciated.

how about

ngOnInit(){
    this._service.GetBars().contactMap(result => {
        this.bars = result;
        return this._service.GetFooBars();
    }).subscribe(
        data => {
            this.foo.bars = data;
            setSelected();
        },
        err => console.log(err)
        )
}

setSelected(){
    var roleSelect = document.getElementById("role-select");
    this.foo.bars.forEach((v, i) => {
        for (var j = 0; j < roleSelect.options.length; j++) {
            if (roleSelect.options[j].text === v) {
                roleSelect.options[j].selected = true;
            }
        }
    });
}

however, I think you don't really need setSelected function.

In theory, ngModel should take care of that.

if not, in your template, you can add [selected]="bar===foo.bars"

<select id="role-select" class="form-control" [(ngModel)]="foo.bars" multiple>
    <option *ngFor="let bar of bars" [selected]="bar===foo.bars">{{bars}}</option>
</select>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM