简体   繁体   中英

How to use typescript object to render a partial view

As of now I am rendering buttons using an enum and then depending on the type I have different HTML. It goes like so,

export interface control {
  type: controlType;
}

export enum controlType {
  button, 
  switch,
  select
}

Then I can call it like so,

<!--- ko: if: $data.type === 0 -->
  PUT CODE HERE
<!-- /ko -->

I'm trying to help optimization by using an object and then rendering a view of the code in a different file. I can't quite get it to work and any help would be appreciated. So far I have,

export interface control {
  type: {
    button: 'folder/button.html',
    switch: 'folder/switch.html',
    select: 'folder/select.html'
  }
}

Then I thought I could just use something like

<!-- ko compose: { view: $data.type } --> <!-- /ko -->

that doesn't work and I'm stuck.

interface only exists to check your types at build time. Since your type object is defined inside the interface, button: 'folder/button.html', and others don't exists in run time unless you assign $data.type with the exact same object as type in your interface.

Instead, you can define controlType as a string enum :

export enum controlType {
  button = 'folder/button.html', 
  switch = 'folder/switch.html',
  select = 'folder/select.html'
}

export interface control {
  type: controlType;
}

Now, you can create an object of type control like:

const $data: control = {
  type: controlType.button
}

This forces the $data.type have only 3 possible values and allow you to use it like:

<!-- ko compose: { view: $data.type } --> <!-- /ko -->

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