Angular2选择标记的默认值

时间:2017-02-15 21:05:02

标签: angular html-select

我试图为我的选择'设置默认值。根据模型

标记angular2

这是我的代码:

HTML

<div>
  <label>Agence: </label>
  <select [(ngModel)]="candidat.agence">
    <option *ngFor="let agence of agences" [ngValue]="agence">{{agence.nom}}</option>
  </select>
</div>

COMPONENT

export class CandidatDetailComponent implements OnInit {
    @Input()
    candidat: Candidat;

    agences: Agence[];

    constructor(
        private agenceService: AgenceService,
    ) {}

    ngOnInit(): void {
        this.agenceService.getAgences().then(agences => this.agences = agences);
    }
}

AGENCE

export class Agence {
    id: number;
    nom: string;
}

CANDIDAT

export class Candidat {
    id: number;
    nom: string;
    agence: Agence;
}

从另一个组件

中检索候选人属性

显示div时,未设置默认值agence.nom

有人有想法吗?谢谢!!!

2 个答案:

答案 0 :(得分:2)

首先,select必须具有name 属性

<select [(ngModel)]="candidat.agence" name="WHATEVER">

根据显示的code,绑定应该自动发生......也许candidat.agence某些属性与agence不同({{1} } array )。

无论如何,要设置agences,您可以这样做:

candidat

答案 1 :(得分:0)

找到了一个丑陋的解决方法:

CREATE FUNCTION [dbo].[udf-Str-Parse-Row] (@String varchar(max),@Delimiter varchar(10))
Returns Table 
As
Return (
    Select Pos1 = ltrim(rtrim(xDim.value('/x[1]','varchar(max)')))
          ,Pos2 = ltrim(rtrim(xDim.value('/x[2]','varchar(max)')))
          ,Pos3 = ltrim(rtrim(xDim.value('/x[3]','varchar(max)')))
          ,Pos4 = ltrim(rtrim(xDim.value('/x[4]','varchar(max)')))
          ,Pos5 = ltrim(rtrim(xDim.value('/x[5]','varchar(max)')))
          ,Pos6 = ltrim(rtrim(xDim.value('/x[6]','varchar(max)')))
          ,Pos7 = ltrim(rtrim(xDim.value('/x[7]','varchar(max)')))
          ,Pos8 = ltrim(rtrim(xDim.value('/x[8]','varchar(max)')))
          ,Pos9 = ltrim(rtrim(xDim.value('/x[9]','varchar(max)')))
    From  (Select Cast('<x>' + replace((Select replace(@String,@Delimiter,'§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml) as xDim) as A 
)
--Thanks Shnugo for making this XML safe
--Select * from [dbo].[udf-Str-Parse-Row]('Dog,Cat,House,Car',',')
--Select * from [dbo].[udf-Str-Parse-Row]('John <test> Cappelletti',' ')
--Select * from [dbo].[udf-Str-Parse-Row]('A&B;C;D;E, F;<x>',';')

这将候选人的年龄设定为列表中定义的对象

有更清洁的方法吗?