Home>

I am making a screen using Angular.
I want to display a pull-down in the table and receive the selected value in Component, but it doesn't work.
I will write the code below, can you help me?

Applicable source code

templete.html

<button (click) = "btnClicked ()">OK</button>
<ngx-datatable
    #dataTable
    
    [rows] = "_ rows"
    [columns] = "_ columns"
>
<ng-template #sexT let-row = "row" let-value = "value" let-t = "index">
    <select>
        <option [value] = 'undefined'>
            Please select
        </option>
        <option * ngFor = "let sex of row.sex;" [value] = "sex.id">
            {{sex.name}}
        </option>
    </select>
</ng-template>
</ngx-datatable>

component.ts

private _columns = [];
private _rows = [];
private selectedSex: Object;
ngOnInit () {
    this._columns = [
        {prop: 'name', name: 'name'},
        {prop: 'sex', name: 'sex', cellTemplate: this.sexT}
    ];
    this._rows = [
        {
            name: "Test Taro",
            sex: [
                {id: 0, name: "male"},
                {id: 1, name: "woman"}
            ]
        },
        {
            name: "Test Jiro",
            sex: [
                {id: 0, name: "male"},
                {id: 1, name: "woman"}
            ]
        }
    ];
}
btnClicked () {
    console.log ("sex:") // I want to display the selected value here
}
Tried If i bind using

ngModel, changing one of the values ​​will change the other.

template.html

<!-Only changes are listed->
    <select [(ngModel)] = "selectedSex"><!-Added [(ngModel)] = "selectedSex"->
        <option [value] = 'undefined'>
            Please select
        </option>
        <option * ngFor = "let sex of row.sex;" [value] = "sex.id">
            {{sex.name}}
        </option>
    </select>

component.ts

// Only changes are listed
btnClicked () {
    console.log ("sex:" + this.selectedSex) // The desired value is taken, but "Test Taro" and "Test Jiro" will change
}
Supplemental information (FW/tool version etc.)

Angular: 5.1.2

If i know how to solve it, please teach me.

  • Answer # 1

    First of all, try makingselectedSexan array and changing the binding destination ofngModeltoselectedSex [t].
    I think this will meet the requirements.

    private selectedSex = [];
    <select [(ngModel)] = "selectedSex [t]">
        <option [value] = 'undefined'>
            Please select
        </option>
        <option * ngFor = "let sex of row.sex;" [value] = "sex.id">
            {{sex.name}}
        </option>
    </select>

Related articles