2017-12-29 43 views
1

서버에 대한 서비스 호출을 통해 HTML 데이터를 받고 싶었습니다 (물론 템플릿을 로컬로 유지할 수는 없습니다). 그것을 (모달 또는 전체 페이지로) 보여주는 방법. Angular 태그가있는이 HTML은 구성 요소에 반복되어 함께 사용해야합니다. 대부분 Angular JS에서 컴파일됩니다.

저는 Angular 5로 솔루션을 개발 중이며 AOT 컴파일러와 호환되어야합니다. 몇 가지 솔루션을 언급했으며 사용되지 않고 업데이트 된 솔루션에 혼란을 겪었습니다. 도와주세요. 나는 당신의 업데이트 된 답변이 많은 다른 사람들을 도울 것이라고 믿습니다. 미리 감사드립니다!

답변

1

즉시 HTML을 렌더링하려면 DomSanitizer가 필요합니다. 예 : 다음과 같이 입력하십시오.

<!-- template --> 
<div [innerHTML]="htmlData"></div> 

// component 
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 { 
    htmlData: any; 
    constructor(private sanitizer: DomSanitizer) {} 

    ngOnInit() { 
    this.htmlData= this.sanitizer.bypassSecurityTrustHtml('<div style="border: 1px solid red;"><h2>Safe Html</h2><span class="user-content">Server prepared this html block.</span></div>'); 
    } 
} 

이제는 그 주안점입니다. 분명히 적재 정비공이 필요합니다. 또한이 블록에 일부 데이터를 포함 할 수 있습니다 - 그것은 단순한 데이터의 경우, 즉석에서 할 수 있습니다 : 동적 구성 요소를 만들해야 할 수도 있습니다 더 복잡한 시나리오

this.htmlData= this.sanitizer.bypassSecurityTrustHtml(`<div>${this.someValue}</div>`); 

.

편집 : 동적으로 해석되는 구성 요소의 예. 이를 통해 서버에서 보낸 html에서 on-the-fly 구성 요소를 만들 수 있습니다.

@Component({ 
    selector: 'my-component', 
    template: `<h2>Stuff bellow will get dynamically created and injected<h2> 
      <div #vc></div>` 
}) 
export class TaggedDescComponent { 
    @ViewChild('vc', {read: ViewContainerRef}) vc: ViewContainerRef; 

    private cmpRef: ComponentRef<any>; 

    constructor(private compiler: Compiler, 
       private injector: Injector, 
       private moduleRef: NgModuleRef<any>, 
       private backendService: backendService, 
      ) {} 

    ngAfterViewInit() { 
    // Here, get your HTML from backend. 
    this.backendService.getHTMLFromServer() 
     .subscribe(rawHTML => this.createComponentFromRaw(rawHTML)); 
    } 

    // Here we create the component. 
    private createComponentFromRaw(template: string) { 
    // Let's say your template looks like `<h2><some-component [data]="data"></some-component>` 
    // As you see, it has an (existing) angular component `some-component` and it injects it [data] 

    // Now we create a new component. It has that template, and we can even give it data. 
    const tmpCmp = Component({ template, styles })(class { 
     // the class is anonymous. But it's a quite regular angular class. You could add @Inputs, 
     // @Outputs, inject stuff etc. 
     data: { some: 'data'}; 
     ngOnInit() { /* do stuff here in the dynamic component */} 
    }); 

    // Now, also create a dynamic module. 
    const tmpModule = NgModule({ 
     imports: [RouterModule], 
     declarations: [tmpCmp], 
     // providers: [] - e.g. if your dynamic component needs any service, provide it here. 
    })(class {}); 

    // Now compile this module and component, and inject it into that #vc in your current component template. 
    this.compiler.compileModuleAndAllComponentsAsync(tmpModule) 
     .then((factories) => { 
     const f = factories.componentFactories[0]; 
     this.cmpRef = f.create(this.injector, [], null, this.moduleRef); 
     this.cmpRef.instance.name = 'my-dynamic-component'; 
     this.vc.insert(this.cmpRef.hostView); 
     }); 
    } 

    // Cleanup properly. You can add more cleanup-related stuff here. 
    ngOnDestroy() { 
    if(this.cmpRef) { 
     this.cmpRef.destroy(); 
    } 
    } 
} 
+0

답장을 보내 주셔서 감사합니다. HTML보기 만 렌더링 한이 메서드를 시도했습니다. 템플릿의 각도 태그가 함께 작동하도록합니다. – Srini

+0

태그가 제대로 작동하려면 구성 요소를 즉시 부트 스트랩 할 수 있습니다. – Zlatko

+0

@Srini가 수정 된 답변을 확인합니다. – Zlatko