3

I would like to write a component in Angular 2 that displays and highlights HTML code. It should be possible to write the HTML code without needing to escape tags with < and such.

In the end I would like to write something like this:

<my-code-component>
    <span (click)="test()">My test code</span>
</my-code-component>

It should be displayed in the browser like this:

<span (click)="test()">My test code</span>

So the raw HTML code should be shown as is.


In Angular 1, the way to do it would be to register a pre-compile function in a directive, so that it can retrieve the content of the element before it has been compiled by angular. In Angular 2, all I can find is AfterViewInit, which is only executed after the code is already compiled, so the (click) attribute is missing from innerHTML.

Is there any such thing as a pre-compile function in Angular 2?


Another thing that I have discovered is the ngNonBindable attribute. It is supposed to prevent Angular 2 from compiling the element. However, even testing it like this:

<div ngNonBindable>
    <span (click)="test()">My test code</span>
</div>

does not work. Instead, it throws lots of InvalidCharacterError: Failed to execute 'setAttribute' on 'Element': '(click)' is not a valid attribute name. errors, which seems to be related to this bug in the DOM specification.

Is this a bug in Angular 2, or am I doing something wrong?

cdauth
  • 6,171
  • 3
  • 41
  • 49
  • [ngNonBindable](https://github.com/angular/angular/blob/master/modules/angular2/test/common/directives/non_bindable_spec.ts) seems to work only with interpolation. It looks like it's trying to compile something that it shouldn't, I mean, if you put that inside ngNonBindable angular2 shouldn't care about it and shouldn't throw. So I can't say for sure, maybe you could ask for it as a feature. – Eric Martinez Mar 10 '16 at 15:21

1 Answers1

0

In fact (click) is not a valid attribute name, at least in Chrome you can't add an attribute named (click). Therefore this only works when Angular preprocesses the HTML and resolves the bindings before it adds the template to the DOM.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • `(click)` is a valid attribute name [by the HTML standard](https://www.w3.org/TR/html5/syntax.html#attributes-0) (see also [here](http://stackoverflow.com/questions/925994/what-characters-are-allowed-in-an-html-attribute-name)), it is just not a valid argument to `setAttribute()` (whose [standard](https://dom.spec.whatwg.org/#dom-element-setattribute) refers to [the XML standard](https://www.w3.org/TR/xml/#NT-Name)). – cdauth Mar 10 '16 at 15:48
  • That's what I remembered, but I wasn't able to add it in Chrome devtools. Chrome just removed it. – Günter Zöchbauer Mar 10 '16 at 15:49