0

I have an existing .NET application that I want to update to use an Angular 2 front-end. There is a section of a page that has dynamic content and every time I want to get the most up-to-date content, I currently use jquery similar to this:

$.get("/Plan/Variety/VarietyList")
            .done(function (data) {
                PlaceReturnedData($("body"), data, "variety-list-selling");
            });

The data returned is the exact HTML I need, no need to manipulate it.

How can I use Angular 2 to return this same data? I've looked around and only see how to handle JSON data, such as the example below from Angular 2's Tour of Heroes tutorial:

heroes.component.ts:

heroes: Hero[];
selectedHero: Hero;

constructor(
    private router: Router,
    private heroService: HeroService
) { }

getHeroes(): void {
    this.heroService.getHeroes().then(heroes => this.heroes = heroes);
}

ngOnInit(): void {
    console.log('initializing MenuVarietiesComponent');
    this.getHeroes();
}

hero.service.ts

@Injectable()
export class HeroService {
    private heroesUrl = 'app/heroes';  // URL to web api
    private headers = new Headers({'Content-Type': 'application/json'});

    constructor(private http: Http){ }

    getHeroes(): Promise<Hero[]> {
        return this.http.get(this.heroesUrl)
                   .toPromise()
                   .then(response => response.json().data as Hero[])
                   .catch(this.handleError);
    }
}

heroes.component.html:

<ul class="heroes">
    <!-- On click, execute onSelect() function and pass in the hero variable from the ngFor. Apply the "selected" class if hero & selectedHero match, remove it if they don't -->
    <li *ngFor="let hero of heroes" 
        (click)="onSelect(hero)" 
        [class.selected]="hero === selectedHero">
        <span class="badge">{{hero.id}}</span>
        <span>{{hero.name}}</span>
        <!-- We need to stop propagation so we don't trigger the onSelect() method on the <li> -->
        <button class="delete" (click)="delete(hero); $event.stopPropagation()">x</button>  
    </li>
</ul>

How can I modify the example Angular 2 code above to handle HTML data rather than JSON data so I can take advantage of code I already have set up on the C# end? I'm guessing the *ngFor in the html is irrelevant since I probably won't need to save my data as an array and I would probably need to change the value of heroesUrl to /Plan/Variety/VarietyList, but I'm a little stuck after that.

EDIT: Here is what the returned HTML from my controller might look like:

    <div class="varietyTypeName" data-toggle="collapse" data-target="" aria-expanded="true" aria-controls="">
        Greens
        <i class="fa fa-angle-down arrow-toggle"></i>
    </div>
    <div class="collapse in collapsableArea">
        <div class="varietyFamilyName">Arugula</div>            
        <div class="varietyName">
            <a class="ajax-rep rep-main-col" href="/Plan/Selling/DetailsPPVS/5409">Astro</a>
            <a href="#deleteVarietySelling" id="deleteVarietySelling_5409" class="quick-delete fa-minus-button" title="Delete" data-toggle="modal">
                <i class="fa fa-minus"></i>
            </a>
        </div>
    </div>
    <div class="collapse in collapsableArea">
        <div class="varietyFamilyName">Kale</div>                 
        <div class="varietyName">
            <a class="ajax-rep rep-main-col" href="/Plan/Selling/DetailsPPVS/3720">Kalettes</a>
            <a href="#deleteVarietySelling" id="deleteVarietySelling_3720" class="quick-delete fa-minus-button" title="Delete" data-toggle="modal">
                <i class="fa fa-minus"></i>
            </a>
        </div>
    </div>
4
  • How does html look like? Commented Oct 4, 2016 at 17:53
  • Which HTML? My .NET controller returns the exact HTML that I need (no need to format it with Angular) and it should be placed inside of <menu-varieties></menu-varieties>. Does that answer your question? Commented Oct 4, 2016 at 18:38
  • you say - controller returns exact HTML. what HTML that is what I'm asking.... show me that HTML code... Commented Oct 4, 2016 at 18:40
  • I edited my post to include that. Commented Oct 4, 2016 at 19:24

1 Answer 1

1

What you need to do is something like this:

import {Component, OnInit} from '@angular/core';
import {DomSanitizationService} from "@angular/platform-browser";

export class SideBarComponent implements OnInit {
    myHTML;

    constructor(private sanitizer: DomSanitizationService, private myService : MyHTTPService){

        myService.getHTMLFromBackend().subscribe(
            data => {
                    this.myHTML = this.sanitizer.bypassSecurityTrustHtml(data.content)
            });
        }
    ngOnInit() {}
}

Then when you are trying to use it in the html (DOM) Just simply do

{{myHTML}}
Sign up to request clarification or add additional context in comments.

5 Comments

Does this code assume I have a file with a class called MyHTTPService? What do I put in that file?
Yes you need to create a service file like: import {Injectable, EventEmitter} from '@angular/core'; @Injectable() export class MyHTTPService{ constructor() {} getHTMLFromBackend(){ //Perform http call here and simply return it }
I may be missing something, but it looks like you have an extra closing brace. Was subscribe( supposed to be subscribe{, or was that closing brace before ngOnInit(){} supposed to be a ) ?
I'm also not sure how to return the html. I've been modifying examples I've found and can't get it to work.
I've edited the main post to match the changes, I was indeed missing a )

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.