Angular 4, как использовать innerHtml с * ngFor? - PullRequest
0 голосов
/ 12 октября 2018

У меня ниже ответ от API

[  
   {  
      "Cinema_strName":"dfdsfsd, Ahmedabad",
      "Cinema_strID":"HIWB",
      "Cinema_strBannerImg":"F&BCombo.jpg",
      "cinema_addr":"fsdfsdfr,Drive-in Road, 380052, ",
      "cinema_loc":"<iframe src=\"fsdfsdfdsfsfdsfdsffsf4!2i768!4f13.1!3m3!1m2!1s0x0%3A0x6a9f5938cfed5cd2!2sCarnival+Cinemas!5e0!3m2!1sen!2sin!4v1467809324170\" width=\"600\" height=\"450\" frameborder=\"0\" style=\"border:0\" allowfullscreen></iframe>",
      "cinema_mob":0
   }
]

Я хочу получить iframe из API и добавить к карте Div

Для этого я написал в TS файл

  this.common.createAPIService('api/cinemas/List?CityName='+city, '').subscribe((result: any) => {
  if(result.length){
    this.cinema = result;
    console.log(this.cinema);
  }else{
      alert('Cinema not found');
  }
})

HTML-шаблон:

<div class="map" *ngFor="let map of cinema">
     <div [innerHTML]="map.cinema_loc"></div>
 </div>

Но HTML не приходит, но если я связываюсь нормально, как показано ниже

<div class="map" *ngFor="let map of cinema">
     <div>{{map?.cinema_loc}}</div>
  </div>

Iframe при отображении втекстовый формат.

Как мне добавить html?

Пожалуйста, помогите.

В соответствии с данным решением, которое я пробовал ниже

 this.common.createAPIService('api/cinemas/List?CityName='+city, '').subscribe((result: any) => {
  if(result.length){
    this.cinema = result;
    this.cinema = this.sanitizer.bypassSecurityTrustHtml(this.cinema);

    console.log(this.cinema);
  }else{
      alert('Cinema not found');
  }

Но развене работает.Если я console.log this.cinema.cinema_loc.Становится неопределенным.

Ответы [ 4 ]

0 голосов
/ 12 октября 2018

Просто выполните следующие проверки -

  1. Все, что связано с динамическим внедрением html, должно пройти DomSanitizer.Это можно сделать с помощью @Injecting DomSanitizer и вызова метода bypassSecurityTrustHtml.

  2. Убедитесь, что iframe src, который вы передаете, правильный.

Здесь вы можете увидеть демонстрацию в действии - https://stackblitz.com/edit/angular-ixzyza

Примечание. В демонстрационной ссылке я использую https://www.w3.org/TR/PNG/iso_8859-1.txt в качестве источника iframe.

0 голосов
/ 12 октября 2018

Я думаю, это будет работать.Первое решение:

<ng-container *ngFor="let testString of testStrings">
<label [innerHtml]="testString"></label>
</ng-container>

, а второе решение:

this.testString = this.sanitizer.bypassSecurityTrustHtml(this.testString);
0 голосов
/ 12 октября 2018

Похоже, ваша переменная map не определена при первом проходе по какой-то причине.Попробуйте эту модификацию к предыдущему ответу:

<div [innerHTML]="map?.cinema_loc"></div>

0 голосов
/ 12 октября 2018

Вам придется санировать его, так как Angular удаляет его из соображений безопасности:

Использовать это в шаблоне:

<div class="map" *ngFor="let map of cinema">
  <div [innerHTML]="safeCinema(map.cinema_loc)"></div>
</div>

Использовать это в компоненте:

import { Component } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular';

  constructor(private sanitizer: DomSanitizer) {}

  cinema = [
    {
      "Cinema_strName": "dfdsfsd, Ahmedabad",
      "Cinema_strID": "HIWB",
      "Cinema_strBannerImg": "F&BCombo.jpg",
      "cinema_addr": "fsdfsdfr,Drive-in Road, 380052, ",
      "cinema_loc": "<iframe src=\"fsdfsdfdsfsfdsfdsffsf4!2i768!4f13.1!3m3!1m2!1s0x0%3A0x6a9f5938cfed5cd2!2sCarnival+Cinemas!5e0!3m2!1sen!2sin!4v1467809324170\" width=\"600\" height=\"450\" frameborder=\"0\" style=\"border:0\" allowfullscreen></iframe>",
      "cinema_mob": 0
    }
  ];

  safeCinema(cinemaLoc) {
    return this.sanitizer.bypassSecurityTrustHtml(cinemaLoc);
  }

}

Вот Образец StackBlitz для вашей ссылки.

...