Obłaskawiania Angulara ciąg dalszy (po tym problemie).
Tym razem chciałbym stworzyć element. Mógłbym to zrobić co prawda bezpośrednio w szablonie. Jednak przy tworzeniu muszę wykonać parę rzeczy, a dokumentacja Angulara odradza interpolację zbytniej logiki. Tak więc chciałbym jakoś inaczej to zrobić.
Bez Angulara zrobiłbym to tak:
HTML:
<div id="someContainer">
</div>
JavaScript:
const createSomeElement = function() {
const someElement = document.createElement("DIV");
const content = "lalala"; // in fact some heavy computations
const contentElement = document.createTextNode(content);
someElement.appendChild(contentElement);
return someElement;
}
const someContainer = document.getElementById("someContainer");
someContainer.appendChild(createSomeElement());
Z Angularem próbowałem tak:
app.component.html
:
<!-- Sposób nr 1 -->
<div id="someContainer">
{{ createSomeElement() }}
</div>
<!-- Sposób nr 2 -->
<div [innerHtml]="createSomeElement()">
</div>
app.component.ts
:
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
createSomeElement = function() {
const someElement = document.createElement("DIV");
const content = "lalala"; // in fact some heavy computations
const contentElement = document.createTextNode(content);
someElement.appendChild(contentElement);
return someElement;
}
}
Jednak to nie działa, w przypadku obu sposobów wyświetlany jest zamiast "lalala" napis "[object HTMLDivElement]" (zgodnie zresztą z moimi oczekiwaniami).
UPDATE: Zaktualizowałem kod JavaScript w app.component.ts
.
PS. Pytam o tak prostą rzecz, ponieważ chcę uniknąć nauki zbyt wielu nowych rzeczy naraz. Wolałbym krok po kroku wprowadzać się w funkcjonalności, które oferuje Angular. Dlatego też proszę o jak najprostsze rozwiązanie.