iT邦幫忙

2024 iThome 鐵人賽

DAY 7
0

前天確認了設定檔的格式,
是時候來補上一些其他的基本格式了,
之前我們只有加入輸入框的部分,
現在來加入一些比較特殊但也相當常用的元件

首先就是相當常使用到的下拉選單dropdown,
或許是說select,
這邊我們用html的select,
下拉選單的內容option由設定檔傳入,
從這邊開始應該就會很常用到option了,
像是checkbox跟radiobutton應該都會需要選項 ,
這邊會開始在設定檔裡面增加option,
裡面為具有label跟value的陣列

首先一樣在element下面增加base-select

ng g component base-select

然後寫一下基本的下拉選單

// base-select.component.ts  ts的部分可以先跟其他base一樣
    @Input() fieldSetting!: FieldSetting;
    @Input() fieldObj!: any;
    value!: string;

    constructor() { }

    ngOnInit(): void
    {
        this.value = this.fieldObj[this.fieldSetting.name];
    }

    valueChange()
    {
        this.fieldObj[this.fieldSetting.name] = this.value;
    }


// base-select.component.html
<div>
  <select (change)="valueChange()" [(ngModel)]="value">
    <option *ngFor="let option of fieldSetting.options" [value]="option.value">
      {{ option.label }}
    </option>
  </select>
</div>

在element.model裡面增加option的interface

export interface OptionItem
{
    label: string;
    value: string;
}

也調整設定檔的interface 增加options

export interface FieldSetting
{
    name: string;
    cname: string;
    inputType: string;
    placeholder: string;
    required: boolean;
    defaultValue?: string | undefined;
    options?: OptionItem[]; //增加此項目
}

然後我們在main裡面增加一組下拉選單的設定

    {
        name: 'select1',
        cname: '下拉選單1',
        inputType: 'select',
        placeholder: '請選擇',
        required: true,
        options: [
            { label: '選項1', value: '1' },
            { label: '選項2', value: '2' },
            { label: '選項3', value: '3' },
        ]
    }

當然也不要忘了在field.component.html裡面增加base-select的模板

  <div *ngSwitchCase="'select'">
    <app-base-select
      [fieldSetting]="fieldSetting"
      [fieldObj]="fieldObj"
    ></app-base-select>
  </div>

依循之前base的架構下,
增加select並沒有很困難,
接下來還會陸續補上checkbox跟radiobutton的部分,
另外ts的部分重複性也是滿高的,
等其他部分補完應該可以另外再做處理,
今天就先到這邊,剩下的明天再繼續

今日程式:day07


上一篇
第6天 資料綁定
下一篇
第8天 單選元件radio
系列文
簡單的事 最困難-Angular動態Form元件14
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言