Angular2&TypeScript:在html中使用enum顯示相應內容: {{}}和select

在ts中獲取的數據爲number類型,想在html中顯示爲對應的文字。css

須要在ts中指定枚舉類型的引用變量:html

 

ts:typescript

 
@Component({
    selector: 'pakcage-privilege',
    templateUrl: './package-privilege.component.html',
    styleUrls: ['./package-privilege.component.css']
})

export class PackagePrivilegeComponent{

packages: Package[];

DataType:typeof DataType=DataType; TextType:typeof TextType=TextType;
}

interface Package {
    id: String;
    issueId: String;
    issueName: String;
    zipId: String;
    zipName: String;
    dataType: number;
    textType: number;
    fileSize: number;
    url: String;
    createDate: String;
    note: String;
}

enum DataType {
    發明1 = 1,
    新型2 = 2,
    外觀3 = 3,
    受權4 = 4,
    類型5 = 5,
    類型6 = 6
}

enum TextType {
    著錄項1 = 1,
    全文pdf2 = 2,
    全文以及附圖3 = 3
}

 

htmlangular2

<tbody>
   <tr *ngFor="let item of packages">
         <th scope="row">{{item.id}}</th>
         <td>{{item.issueId}}</td>
         <td>{{item.issueName}}</td>
         <td>{{item.zipId}}</td>
         <td>{{item.zipName}}</td>
         <td>{{DataType[item.dataType]}}</td>
         <td>{{TextType[item.textType]}}</td>
         <td>{{item.fileSize}}</td>
         <td>{{item.createDate}}</td>
    </tr>
</tbody>

 

/*2017.9.29更新*/angular4

當須要利用enum顯示爲selectionthis

htmlurl

<tr>
      <th>數據類型</th>
      <td> 
            <select class="form-control" [(ngModel)]="package.dataType" (ngModelChange)="changeOption()">
                 <option *ngFor="let key of dataTypeKeys" [value]="key" [label]="DataType[key]"></option>
             </select>                                                    
       </td>
 </tr>

tsspa

ngOnInit(): void {
       this.dataTypeKeys = Object.keys(this.DataType).filter(f=>!isNaN(Number(f)));
}

changeOption():void{
//execution when change options in select.
}

 

參考:.net

https://www.gurustop.net/blog/2016/05/24/how-to-use-typescript-enum-with-angular2/code

https://stackoverflow.com/questions/35750059/select-based-on-enum-in-angular2

/*2017.10.30*/

https://stackoverflow.com/questions/46998065/onchange-not-working-for-angular4-select-in-dropbox       //(關於option改變時change和ngModelChange的區別)

相關文章
相關標籤/搜索