10

Trying out typescript, I want to achieve the following thing:

Getting a question text and a number from server and displaying it in DOM somewhere, using typescript.

Currently I have the following .ts file:

class QuestionResponse {
    constructor(public questionText, public questionNumber) {
    }
}
function questioner(question: QuestionResponse) {

    return '<div data-val-id="${QuestionNumber}"> ${QuestionText} </div>';
}

var testQuestion = new QuestionResponse("Question text number 5", 5);

//this will be replaced by .innerHTML of some element:
alert(questioner(testQuestion));

This does not replace the ${QuestionNumber} with the question.QuestionNumber... nor the Text. I don't want to use string appends, I want to use clean html, preferably on a seperate .html file.

Basically I'm asking: Is it possible using typescript, if yes, how? If not, what would be the best practice way to achieve this using angularjs? (but still using typescript)

Alon Amir
  • 4,913
  • 9
  • 47
  • 86
Ziv Weissman
  • 4,400
  • 3
  • 28
  • 61
  • 1
    In order to use the string template feature you have to use backticks (same key as `~`) instead of the single tick `'`. – Brocco Aug 17 '15 at 11:58

1 Answers1

15

The correct syntax is:

function questioner(question: QuestionResponse) {
    return `<div data-val-id="${question.questionNumber}"> ${question.questionText} </div>`;
}

The important part here is the usage of ` (backquote/backtick)
Wrap your string with ` instead of " and ' to make use of the ${} syntax.

This is a TypeScript (and ES6) feature.

Alon Amir
  • 4,913
  • 9
  • 47
  • 86
  • K tnx, that did the trick, is it possible to use this `...html...` on an external html file? – Ziv Weissman Aug 17 '15 at 12:10
  • You can only use this feature within the context of a string in typescript, or ES6. However if you use an *IDE* such as *webstorm*, it will detect that you're composing an HTML string and will "treat" it as such. Also in *webstorm*, you can press **alt+enter** to access additional related features. – Alon Amir Aug 17 '15 at 12:27